Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: window.setTimeout(), force early expire

I have a <div> on my page that refreshes automatically every two minutes with updated log entries. When I first load my webpage, I call the following function.

function getLogs() {
    var filter = $('#filter').val();
    $.get("index-ajax.asp", { queryType: "getLogs", filter: filter, 
        uTime: new Date().getTime() },

        function(data){
            $("#logEntries").html(data);
            window.setTimeout("getLogs()",120000);
    });
}

I know the above code could be cleaner with window.setInterval(...); but I just like the control of window.setTimeout(...);.

My question, is it possible to cancel the next timeout execution? In the event that I change the filter, I'd like to cancel the next timeout, and call the function right away, which would reschedule the timeout function. Is there a better way to achieve that result?

Note that the above code is in jQuery.

like image 940
dangowans Avatar asked Dec 01 '25 15:12

dangowans


2 Answers

Yes, use clearTimeout.

Ex:

var clr = window.setTimeout(getLogs,120000);

The when you wan to clear it:

clearTimeout(clr);
like image 133
j08691 Avatar answered Dec 03 '25 04:12

j08691


setTimeout returns a timerID that you can pass to clearTimeout:

// Note we are passing the *function* rather than a string
// Also note the lack of () - we are *not* calling the function
// setTimeout will do that for us
var timerID = setTimeout(getLogs, 120000);
// Fake condition - we cancel the timer if the timerID is even
if (timerID % 2 === 0) {
    clearTimeout(timerID);
}
like image 31
Sean Vieira Avatar answered Dec 03 '25 05:12

Sean Vieira



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!