tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

debounce.js (1221B)


      1 /* This Source Code Form is subject to the terms of the Mozilla Public
      2 * License, v. 2.0. If a copy of the MPL was not distributed with this
      3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
      4 
      5 "use strict";
      6 
      7 /**
      8 * Create a debouncing function wrapper to only call the target function after a certain
      9 * amount of time has passed without it being called.
     10 *
     11 * @param {Function} func
     12 *         The function to debounce
     13 * @param {number} wait
     14 *         The wait period
     15 * @param {object} scope
     16 *         The scope to use for func
     17 * @return {Function} The debounced function, which has a `cancel` method that the
     18 *                    consumer can call to cancel any pending setTimeout callback.
     19 */
     20 exports.debounce = function (func, wait, scope) {
     21  let timer = null;
     22 
     23  function clearTimer(resetTimer = false) {
     24    if (timer) {
     25      clearTimeout(timer);
     26    }
     27    if (resetTimer) {
     28      timer = null;
     29    }
     30  }
     31 
     32  const debouncedFunction = function () {
     33    clearTimer();
     34 
     35    const args = arguments;
     36    timer = setTimeout(function () {
     37      timer = null;
     38      func.apply(scope, args);
     39    }, wait);
     40  };
     41 
     42  debouncedFunction.cancel = clearTimer.bind(null, true);
     43 
     44  return debouncedFunction;
     45 };