您的代码有几个问题。一个是你在一个你已经在函数外部声明的函数内部声明变量(在你的if-else
的else
部分内),另一个是一旦你调用window.setInterval()
方法,你无法阻止它每秒被调用一次永恒。
你的目标是增加x
的值,直到达到random
的值,然后重新开始。在这里,window.setTimeout()
方法更适合你的目的。考虑以下...
/* 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);
如果出于某种原因,你想停止count()
下一个电话就可以了timer
变量传递给window.clearTimeout()
方法,像这样。
/* clear Timeout */
clearTimeout(timer);
参见:WindowTimers @ MDN和this classic StackOverflow answer关于JavaScript的变量范围。
谢谢你的回答非常好! –