CoolFace
Apppublic

opusdev/vector-similarity-api

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes
throttle.js45 linesDownload Raw Back to helpers
1/**2 * Throttle decorator3 * @param {Function} fn4 * @param {Number} freq5 * @return {Function}6 */7function throttle(fn, freq) {8  let timestamp = 0;9  let threshold = 1000 / freq;10  let lastArgs;11  let timer;12 13  const invoke = (args, now = Date.now()) => {14    timestamp = now;15    lastArgs = null;16    if (timer) {17      clearTimeout(timer);18      timer = null;19    }20    fn(...args);21  }22 23  const throttled = (...args) => {24    const now = Date.now();25    const passed = now - timestamp;26    if ( passed >= threshold) {27      invoke(args, now);28    } else {29      lastArgs = args;30      if (!timer) {31        timer = setTimeout(() => {32          timer = null;33          invoke(lastArgs)34        }, threshold - passed);35      }36    }37  }38 39  const flush = () => lastArgs && invoke(lastArgs);40 41  return [throttled, flush];42}43 44export default throttle;45