0

I'm trying to create a javascript counter that starts at 25 minutes and ends at 0. the idea is to show the minutes/seconds as a countdown clock on the page (my target div is called 'txt'). But I'm not getting my desired result - the timer does not subtract each time the function is run (every ms). Any ideas on where I'm going wrong? Code is below:

function countdown() {

    var target = 1500000; // 25 mins
    var current = 1000; // 0 secs

    for (var i=0; i<5; i++) {
        var diff = target-current;           // calculates the 25 minutes
        var min = Math.floor(diff/1000/60);  //gets mins
        var sec = (diff/1000) % 60;          // gets secs
        current = current+1000;

        document.getElementById("txt").innerHTML = min + ":" + sec;
        var t = setTimeout(countdown, 2500);}
    }

}
Nelson Teixeira
  • 6,297
  • 5
  • 36
  • 73
vaspv
  • 25
  • 6
  • 2
    Possible duplicate of [The simplest possible JavaScript countdown timer?](http://stackoverflow.com/questions/20618355/the-simplest-possible-javascript-countdown-timer) – dippas May 10 '16 at 23:02
  • Once your issue is fixed, you should only call *setTimeout* if `diff >= 0`, otherwise it keeps running unnecessarily. – RobG May 10 '16 at 23:14
  • @RobG - thanks. Yes will add that so that it stops when diff reaches 0. – vaspv May 11 '16 at 00:20

2 Answers2

1

You need to define current outside of your function. Currently you are resetting it to 1000 every time the function is run.

Tyler
  • 1,705
  • 2
  • 18
  • 26
  • thanks for clarifying. I was suspecting that (resetting to 1000) but (wrongly) thought the Timeout function would take care of that. – vaspv May 11 '16 at 00:21
0

here you go:

var target = 1500000; // 25 mins
var current = 0; // 0 secs
function countdown() {
    current += 1000;
    var diff = target-current;           // calculates the 25 minutes
    var min = Math.floor(diff/1000/60);  //gets mins
    var sec = (diff/1000) % 60;          // gets secs

    document.getElementById("txt").innerHTML = min + ":" + sec;
    if (diff > 0)
        setTimeout(countdown, 1000);

}

countdown();

JSFiddle with running example: https://jsfiddle.net/epcmw0uc/5/

Nelson Teixeira
  • 6,297
  • 5
  • 36
  • 73