Search code examples
javascriptcountdown

Count down from same number to zero in different time intervals


I'm trying to write a function which should decrease a certain number (let's say 1000) to zero, in a given time. For example, decrease 1000 to 0 in 17 seconds.

I'm stuck at this basic countdown... how could I make it decrease the number, taking into account that it should take x seconds to reach zero?

function update()
{
    xElement.innerHTML = maxscore-(new Date - start);
    setTimeout(update, 1);
}

Solution

  • Here, this code solves the problem:

    var value = 1000;  // Starting value
    var duration = 17000;  // Milliseconds
    var startTime = Date.now();
    
    function update() {
        var elapsed = Date.now() - startTime;
        var t = elapsed / duration;
        if (t < 0) t = 0;
        if (t > 1) t = 1;
        // Now t is a real number in from 0.0 to 1.0
    
        var currentValue = (1 - t) * value;  // Goes from 1000.0 to 0.0
        xElement.innerHTML = Math.round(currentValue).toString();
        if (elapsed < duration)
            setTimeout(update, 1);
    }
    
    update();
    

    Live demo: https://jsfiddle.net/utued9vc/