UNPKG

fenzhi-utils

Version:

分值前端项目的js函数库

108 lines (91 loc) 2.89 kB
/** * 函数防抖:fn函数在最后一次调用时刻的delay毫秒之后执行! * @param fn 执行函数 * @param delay 时间间隔 * @param isImmediate 为true,debounce会在delay时间间隔的开始时立即调用这个函数 * @returns {Function} */ /* // 测试一: let count = 0; const fn = () => count++; // const debouncedFn = () => fn(); const debouncedFn = CustomDebounce(fn, 500); debouncedFn(); debouncedFn(); debouncedFn(); setTimeout(() => { console.log(count); }, 600); // 测试二: const consoleFn = () => console.log(+new Date()); let testFn = CustomDebounce(consoleFn, 500); let count = 0; let timerSign = setInterval(() => { testFn(); if (count > 30) clearInterval(timerSign); count++; }, 100); */ export function CustomDebounce(fn, delay = 100, isImmediate = false) { var timer = null; // 初始化timer,作为计时清除依据 return function () { var context = this; // 获取函数所在作用域this var args = arguments; // 取得传入参数 clearTimeout(timer); if (isImmediate && timer === null) { fn.apply(context, args); // 时间间隔外立即执行 timer = 0; return; } timer = setTimeout(function () { fn.apply(context, args); timer = null; }, delay); }; } /* // 测试fn被正常调用 test('CustomDebounce - fn is called once when called multiple times within the delay time', () => { let count = 0; // 模拟重复调用fn函数 const fn = () => count++; // 使用CustomDebounce包装fn函数 const debouncedFn = CustomDebounce(fn, 500); // 调用debouncedFn函数,模拟在500ms内调用了多次 debouncedFn(); debouncedFn(); debouncedFn(); // 延迟510ms后检查count值是否仅增加了一次 return new Promise((resolve) => { setTimeout(() => { expect(count).toBe(1); resolve(); }, 510); }); }); // 测试isImmediate为true时,fn立即执行 test('CustomDebounce - fn is called immediately when isImmediate is true', () => { let count = 0; // 模拟重复调用fn函数 const fn = () => count++; // 使用CustomDebounce包装fn函数,并指定isImmediate为true const debouncedFn = CustomDebounce(fn, 500, true); // 调用debouncedFn函数 debouncedFn(); // 检查count值是否被增加了一次 expect(count).toBe(1); }); // 测试fn能够正常接收参数 test('CustomDebounce - fn can receive arguments', () => { let num = 0; // 模拟重复调用fn函数 const fn = (n) => num += n; // 使用CustomDebounce包装fn函数,并指定delay参数为0 const debouncedFn = CustomDebounce(fn, 0); // 调用debouncedFn函数,并传入一个参数 debouncedFn(5); // 检查num值是否被增加了5 expect(num).toBe(5); }); */