atol ikan
atol ikan

Reputation: 90

SetInterval/SetTimeout with Countdown Display

I want to have a function set to run at an interval

setInterval(function, 360000);

When it's called, it will load some info from Ajax/Flask, but won't refresh or reload the page.

How can I display a countdown in a div that shows time remaining until the function/interval is next triggered?

Upvotes: 2

Views: 2757

Answers (1)

Michael Geary
Michael Geary

Reputation: 28880

Instead of using a very long timer (six minutes in the code you listed), use a much shorter timer, e.g. a one second timer. Update your div each time that timer fires, and keep track of how many times it gets called. For example:

var secondsBetweenActions = 360;
var secondsRemaining = secondsBetweenActions;
setInterval( function() {
    updateStatus( secondsRemaining );
    secondsRemaining--;
    if( secondsRemaining <= 0 ) {
        doAction();
        secondsRemaining = secondsBetweenActions;
    }
}, 1000 );

Now you just need to implement updateStatus() which should display secondsRemaining in your status div using jQuery, and doAction() which does whatever you need to do.

Upvotes: 3

Related Questions