Js function tremble and throttling difference
Function buffering: The function is executed only once within n seconds after the high-frequency event is triggered. If the high-frequency event is triggered again within n seconds, the time is recalculated. For example, if a character’s skill is interrupted, then the skill is released again and the release time is recalculated. Function throttling: High-frequency events fire, but only execute once in n seconds, so throttling dilutes the execution frequency of the function. This is equivalent to a game character with a bully release ability that cannot be interrupted. 3 seconds per skill, no matter what happens in between.
Image stabilization function
function debounce(fn, delay) {
var timer = null;
return function() {
clearTimeout(timer);
var that = this,
args = arguments;
timer = setTimeout(function() {
fn.apply(that, args)
}, delay)
}
}
Copy the code
Typically used for input or SRCOLl events. Input field searches prevent input from sending too many requests to the back end too quickly, by limiting how long it takes to execute one. Repeated operations recalculate the time.
Throttling function
function throttle(fn, delay) {
var timer = null,
flag = false;
return function() {
if (flag) {
return
}
flag = true
var that = this,
args = arguments;
timer = setTimeout(function() {
clearTimeout(timer);
flag = false
fn.apply(that, args)
}, delay)
}
}
Copy the code
Generally used for mousemove or REsize events, avoid triggering N events, limit the number of milliseconds can be executed only once, improve performance.
My blog and GitHub address
github.com/lanpangzhi
blog.langpz.com