Oh wait, I think I see what you’re trying to do, and why it’s not working.
I misunderstood your original post. Apologies.
setInterval doesnt re-evaluate the timer on every loop - it resolved your random value, came up with a number (somewhere in the range of 2000-2099), and said “every X milliseconds, run this function.”
What you’re doing here, is start a function. That function sets a new timer, which re-evaluates the random modifier, every loop.
Well explained, … mili seconds so the random number will always be between 0 and 1 eg .9999 or .0001 so to get the right effect I should increase the multiplier
just put example in spreadsheet with different random numbers between 0 and 1 do the calculation there will always be a small variant so this will not work
Hi @johan40, you don’t need to clear anything if you’re using setTimeout(), just don’t start the next one…
var timeLeft = 479
function countdown () {
console.log(timeLeft)
timeLeft--
if (timeLeft > 470) {
setTimeout(countdown, 200 + Math.random() * 100)
}
}
countdown()
Fun fact: clearTimeout() and clearInterval() can be used interchangeably as their handles are sharing the same pool… although you should of course always use the correct one to avoid readability mayhem. ^^
Not really though I’m afraid – the countdown only stops because downloadTimer is not defined, so clearInterval(downloadTimer) will throw a reference error… which is a rather drastic measure at any rate. And if it was defined the countdown would keep going in the background, you’d just not print the current time left to the screen; have a look at post #12 how to actually terminate the countdown.
Which is… accurate, but for the benefit of describing what it is doing, it’s choosing not to do another step in the countdown.
Your countdown timer is, in fact, just a function that decrements a value.
What makes it a timer is the setTimeout, which runs exactly once.
BUT, your function says, “If the value is more than 470, start a NEW timeout, that runs exactly once, and then executes this function again.”
So clearing this Timeout doesnt make any sense - you don’t want to interrupt the timer between cycles, you want to wait until your value has reached a predetermined value, and then simply stop making new timeouts.
A slight difference, but it is an important distinction - interrupting a cycle, rather than logical execution at the end of a cycle.
No, there’s no need to clear a timeout or interval at all (and downloadTimer still wouldn’t be defined); when using setTimeout() as described earlier, the function basically calls itself until a certain condition is met, and then it just doesn’t schedule the next invocation.