Your code has a couple of problems. One being that you are declaring variables inside a function which you have already declared outside of the function (inside the else
portion of your if-else
), and another being that once you invoke the window.setInterval()
method you have no way of stopping it being called every second unto eternity.
What you are aiming for is to increment the value of x
until it reaches the value of random
, and then start all over again. The window.setTimeout()
method is more suited to your purposes here. Consider the following...
/* generate variable values */
var random = Math.floor(Math.random() * 27) + 3;
var x = 0;
var timer;
/* report the 'random' value */
console.log('random:',random);
function count() {
if (x < random) {
/* report the 'seconds since' value */
console.log(x+1);
/* increment the value */
++x;
/* call this function in 1000ms */
timer = setTimeout(count, 1000);
} else {
/* re-generate variable values */
random = Math.floor(Math.random() * 27) + 3;
x = 0;
/* report the new 'random' value */
console.log(" check");
console.log('random:',random);
/* call this function in 1000ms */
timer = setTimeout(count, 1000);
}
}
/* begin 1s from now */
timer = setTimeout(count, 1000);
If, for whatever reason, you wished to halt the next call to count()
you can pass the timer
variable to the window.clearTimeout()
method, like so.
/* clear Timeout */
clearTimeout(timer);
See also: WindowTimers @ MDN and this classic StackOverflow answer concerning JavaScript variable scope.