Search code examples
javascriptrecursiontimercountdown

Recursive countdown timer


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);}
    }

}

Solution

  • 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/