0

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);
}
binoculars
  • 2,226
  • 5
  • 33
  • 61
  • How many increments do you want in the given time, or how much do you want to reduce it by each time you reduce it until you get to zero. It would just be something like xElement.innerHTML = maxscore-(maxscore/17); if you wanted to decrease it once per second for 17 seconds, but then I think the set timeout time variable would be 10000 for one second but i'm not sure – Andrew Clavin Jul 04 '16 at 20:33

2 Answers2

0

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/

Nayuki
  • 17,911
  • 6
  • 53
  • 80
0

var start = 1000;
var end = 0;
var time = 17000; // in ms

var count = setInterval(function(){
  if (start < 0) {
    clearInterval(count);
  } else {
    console.log(start--);
  }
}, time/start);
dhorelik
  • 1,477
  • 11
  • 14