javascript 为什么 setTimeout() 函数只运行一次?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4524122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why setTimeout() function runs only once?
提问by Shubham
I am making a javascript bookmarklet that resizes all images, periodically.
我正在制作一个定期调整所有图像大小的javascript书签。
javascript: function x(){
for(i=0;i<=document.getElementsByTagName('img').length;i++)
document.getElementsByTagName('img')[i].width+=1;
};
t = window.setTimeout("x()",100);
void(0);
But it runs only once. What is the problem here??
但它只运行一次。这里有什么问题??
回答by BoltClock
Are you looking for setInterval()instead of setTimeout()by any chance?
您是否正在寻找setInterval()而不是setTimeout()任何机会?
t = window.setInterval("x()",100);
回答by Oswald
Here is the same code properly indented for clarity
为了清楚起见,这里是正确缩进的相同代码
function x() {
for(i=0;i<=document.getElementsByTagName('img').length;++)
document.getElementsByTagName('img')[i].width+=1;
};
t = window.setTimeout("x()",100);
void(0);
window.setTimout() executes the passed code only once because it is meant to. If you want to execute code more often, use window.setInterval().
window.setTimout() 只执行一次传递的代码,因为它是故意的。如果您想更频繁地执行代码,请使用 window.setInterval()。
回答by epaps
Shouldn't it be i++at the end of your for loop?
它不应该i++在你的 for 循环的末尾吗?
回答by miqbal
Also there is a syntax error.
还有一个语法错误。
for(i=0;i<=document.getElementsByTagName('img').length;i++)
for(i=0;i<=document.getElementsByTagName('img').length; i++)
回答by gravityboy
You need to put the...
你需要把...
t = window.setTimeout("x()",100);
inside the function x() brackets { } and it works with SetTimeout()
在函数 x() 括号 { } 内,它与 SetTimeout() 一起使用
function x() {
for(i=0;i<=document.getElementsByTagName('img').length;i++)
document.getElementsByTagName('img')[i].width+=1;
t = window.setTimeout("x()",100);
};
x();
void(0);
You can only call x() after all the images have been loaded on the page or there is an error.
您只能在页面上加载所有图像或出现错误后调用 x() 。
回答by Biswanath
It might be window.setTimeOut("x",100)
有可能 window.setTimeOut("x",100)
Edit : correct the answer to this window.setTimeout(x,100).
编辑:更正对此的答案window.setTimeout(x,100)。
PS: thats what happens if you simply work with a IDEs.
PS:如果您只是使用 IDE,就会发生这种情况。

