javascript - 使用 setInterval 随着时间的推移减少变量

标签 javascript html

所以现在,我是编码的初学者,并且在使用 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/

相关文章:

python - bs4 findAll 找不到类标签

javascript - 更改 JSON 时无法读取未定义的属性 'appendChild'

javascript - 实时更新 jquery marquee

javascript - 如何使用vue动态添加before after css代码?

asp经典脚本 block 中使用的Javascript变量

Html Bootstrap - 包装引导轮播以适合呈现的图像

html - 在 Firefox 和 Chrome 48 中使用 flexbox 呈现问题

javascript - 修改数字输入以仅接受数字

javascript - 如何修复此语法错误 : Unexpected identifier?

html - 文本区域滚动条 Firefox 错误