您的代碼有幾個問題。一個是你在一個你已經在函數外部聲明的函數內部聲明變量(在你的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的變量範圍。
謝謝你的回答非常好! –