所以现在,我是编码的初学者,并且在使用 setInterval 命令时遇到了很多问题。我想做的是有一个函数,每经过 5 秒,变量就减少 1。然而,尽管我已经查看了许多不同的线程以及有关 setInterval 命令的信息,但它们似乎都不符合我的需求(尽管我可能错过了一些东西),并且我无法操纵我在其他地方看到的任何内容来执行我的功能。
while (fullness <= 10) {
setInterval(hungry{ fullness--; }, 1000);
}
最佳答案
为什么你的代码是错误的:
//There is no need to loop and call setInterval multiple times
//setInterval will fire the callback function every x milliseconds,
//In your example you have it firing every 1 second(1000 milliseconds)
//while (fullness <= 10) {
//setInterval(hungry{ fullness--; }, 1000);
//}
要解决此问题: 页面加载时(jquery 中的 document.ready) 只需调用一次 setInterval()
setInterval(function(){
if(fullness <= 10){
hungry{ fullness--; }; //Not sure about this line as it comes from your example
}
}, 5000); //Pass second parameter to setInterval of 5000 milliseconds (5 seconds wait)
关于javascript - 使用 setInterval 随着时间的推移减少变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53398909/