All files / fn setLock.ts

100% Statements 10/10
100% Branches 1/1
100% Functions 3/3
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34                                    1x       1x 6x 3x 2x 2x   2x       1x  
/**
 * 包装为触发一次后,预置时间内不能再次触发的函数
 * - 类似于技能冷却。
 * @method setLock
 * @param {Function} fn 要延迟触发的函数
 * @param {Number} delay 延迟时间(ms)
 * @return {Function} 经过包装的冷却触发函数
 * @example
 * import { setLock } from '@spore-ui/tskit';
 * $('#input').keydown(setLock(() => {
 *   console.info('do request');
 * }, 500));
 * // 第一次按键,就会触发一次函数调用
 * // 之后连续按键,仅在 500ms 结束后再次按键,才会再次触发事件函数调用
 */
 
import { TypeTimeout } from '../types';
 
export function setLock(
  fn: Function,
  delay: number,
) {
  let timer: TypeTimeout = null;
  return (...args: unknown[]) => {
    if (timer) return;
    timer = setTimeout(() => {
      timer = null;
    }, delay);
    fn(...args);
  };
}
 
export default setLock;