Skip to content

Instantly share code, notes, and snippets.

@john-yuan
Created January 8, 2019 01:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save john-yuan/0eafd40e6ead52dcc003a33f9c978404 to your computer and use it in GitHub Desktop.
Save john-yuan/0eafd40e6ead52dcc003a33f9c978404 to your computer and use it in GitHub Desktop.
/**
* debounce
*
* @param {number} time time to wait next call
* @param {(...any) => any} callback the callback function
* @returns {(...any) => any}
*/
var debounce = function (time, callback) {
var timer = null;
var slice = Array.prototype.slice;
var exectue = function (args) {
if (args.length === 0) {
callback();
} else if (args.length === 1) {
callback(args[0]);
} else if (args.length === 2) {
callback(args[0], args[1]);
} else if (args.length === 3) {
callback(args[0], args[1], args[2]);
} else {
callback.apply(null, args);
}
};
return function () {
var args = slice.call(arguments);
if (timer !== null) {
clearTimeout(timer);
}
timer = setTimeout(function () {
timer = null;
exectue(args);
}, time);
};
};
// TEST
var fn = debounce(300, function (code) {
console.log(code);
});
fn(100);
setTimeout(function () {
fn(200);
setTimeout(function () {
fn(400);
setTimeout(function () {
fn(500);
}, 500);
}, 400);
}, 200);
// OUTPUT:
// 200
// 400
// 500
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment