Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fire only the very last setTimeout

Tags:

javascript

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?

like image 788
Chef Avatar asked Oct 12 '25 19:10

Chef


2 Answers

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.

like image 37
Mark Rushakoff Avatar answered Oct 14 '25 10:10

Mark Rushakoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!