Shake
The concept: a callback to be triggered in the event n seconds, and then, if this has been triggered in n seconds, then re-timing.
Example: If someone into the elevator, that elevator will start after 10 seconds, then if someone into the elevator, and we have to wait 10 seconds before departure.
Ideas: closure by maintaining a variable, if this variable represents the timing has begun, before the start time if you have emptied the timer to restart timing.
function debounce(fn, time) { let timer = null; return function () { let context = this let args = arguments if (timer) { clearTimeout(timer); timer = null; } timer = setTimeout(function () { fn.apply(context, args) }, time) } } window.onscroll = debounce(function(){ console.log('触发:'+ new Date().getTime()); },1000)
Throttling
Example: cooldown in the game, no matter how many times you press, the skills can only be triggered again after cooling good
function throttle(fn, time) { let canRun = true; return function () { if(canRun){ fn.apply(this, arguments) canRun = false setTimeout(function () { canRun = true }, time) } } } window.onscroll = throttle(function(){ console.log('触发:'+ new Date().getTime()); },1000)