Backed out 2 changesets (bug 1943998) for causing wd failures @ phases.py CLOSED...
[gecko.git] / devtools / shared / debounce.js
blobd43dea48d5065f9bec9a78f3d9eb502e2c2a933f
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/. */
5 "use strict";
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.
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.
20 exports.debounce = function (func, wait, scope) {
21 let timer = null;
23 function clearTimer(resetTimer = false) {
24 if (timer) {
25 clearTimeout(timer);
27 if (resetTimer) {
28 timer = null;
32 const debouncedFunction = function () {
33 clearTimer();
35 const args = arguments;
36 timer = setTimeout(function () {
37 timer = null;
38 func.apply(scope, args);
39 }, wait);
42 debouncedFunction.cancel = clearTimer.bind(null, true);
44 return debouncedFunction;