Created
January 8, 2019 01:29
-
-
Save john-yuan/0eafd40e6ead52dcc003a33f9c978404 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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