简体   繁体   English

js setTimeout() 立即完成,没有任何 rest

[英]js setTimeout() finishes instantly without any rest

when coding, I came upon this very weird problem.在编码时,我遇到了这个非常奇怪的问题。 My code is below: js我的代码如下:js

document.getElementById("id").style.width = "0%"
var a = 0;
setTimeout(function () {
    if (a <= 60) {
        document.getElementById("id").style.width = a + "%";
        a++;
    }
}, 100);


I want it to run 60 times, each time changing the div's width by 1% However, when I run the code, the if block makes it finish instantly as if the timeout didn't work.我希望它运行 60 次,每次将 div 的宽度更改 1% 但是,当我运行代码时,if 块使它立即完成,就好像超时不起作用一样。 Can anyone tell me what's wrong?谁能告诉我怎么了? Thanks in advance!提前致谢!

setTimeout function executes only once after that specified time in milli seconds. setTimeout function 仅在指定时间后执行一次(以毫秒为单位)。

If you want to keep on executing the block, you have to make use of setInterval instead of setTimeout .如果要继续执行该块,则必须使用setInterval而不是setTimeout

setInterval keeps on calling the function since the interval is cleared. setInterval继续调用 function 因为间隔被清除。

Dont forget to call clearInterval once target achieved.一旦目标实现,不要忘记调用clearInterval

 var a = 0; const interval = setInterval(function () { if (a <= 60) { console.log("Im being called"); document.getElementById("id").style.width = a + "%"; a++; } else { // Target achieved, clearing interval console.log("Im stoping execution"); clearInterval(interval) } }, 100);
 #id { height: 300px; background: orange; }
 <div id="id"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM