window.addEventListener('resize', onResize, false);
function onResize() {
timer = setTimeout(function() {
console.log('fire timer');
}, 1000);
}
Resize event fires super fast. So there will be many timer fire every 1000ms. How to fire only the very last timer?
Clear the timer for each call
var timer;
function onResize() {
clearTimeout(timer);
//...
timer = setTimeout(function() {
console.log('fire timer');
}, 1000);
}
(timer
may be null or undefined).
If you're already using underscore.js, you have the debounce method to fill this need:
Creates and returns a new debounced version of the passed function that will postpone its execution until after wait milliseconds have elapsed since the last time it was invoked. Useful for implementing behavior that should only happen after the input has stopped arriving.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With