Search code examples
jqueryhttp-redirecttimersetintervalcountdown

How to go about making a timer that counts down from 5 minutes and then redirect? JQuery


So I've been googling and no codes really match what I want to acheve what I want to do is have a div lets give it the id of Timer5min then in the div have 5:00 so 5 minutes and 0 seconds then I want to have JQuery take it down second by second I assume that would need a setInterval function and then something like:

 $('#Timer5min').text(--sec);

and then setting a second var like so var sec = $('#Timer5min').text();

I'm not a 100% on how to do the mintues though I assume an if statement but this is where i get stuck.... so any idea's?

It would also be nice if when the timer reaches 0 mintues and 0 seconds to have it redirect somewhere...

Thank you for reading :) No plugin answers please xD

Edit Im looking for something similar to this but with mintues as well...:

<div id="Timer5min">

 300 
</div>

var sec = $('#Timer5min').text()
var timer = setInterval(function() { 
   $('#Timer5min').text(--sec);
   if (sec == 10) {
     //redirect
      clearInterval(timer);
   } 
}, 1000);

http://jsfiddle.net/GNrUM/1181/


Solution

  • This should get you what you are looking for. One thing to remember with this solution though, setTimeout isn't guaranteed to fire exactly at 1000 milliseconds so your timer may occasionally be off by a little bit.

    (function() {
        var timer = 301; // 5 minutes worth of seconds + 1 for the first call
    
        function countDown() {
            if (--timer) {
                var minutes = timer % 60;
                if (!minutes) {
                    minutes = '00';
                }
                $('#Timer5min').text(Math.floor(timer/60) + ':' + minutes);
                setTimeout(countDown, 1000);
            } else {
                window.location = 'http://google.com';
            }
        }
    
        countDown();
    })();