JavaScript setTimeout 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13260261/
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
JavaScript setTimeout doesn't work
提问by Ido
I wanted a JavaScript function to run 60 seconds after page is loaded. After a little research I have made, I've found that setTimeout() is the solution.
我想要一个 JavaScript 函数在页面加载后运行 60 秒。经过我的一些研究,我发现 setTimeout() 是解决方案。
So that's what I did:
所以这就是我所做的:
<body onLoad="setTimeout(postAction('news.reads', 'article'), 60000);">
Somehow, setTimeout does not work. After the page is loaded, there's no need to wait 60 seconds because postAction() runs immediately.
不知何故, setTimeout 不起作用。页面加载后,不需要等待 60 秒,因为 postAction() 会立即运行。
Why is it happening? How to solve it? Are there alternatives to setTimeout() up there? Thank you!
为什么会发生?如何解决?那里有 setTimeout() 的替代方案吗?谢谢!
采纳答案by Elias Van Ootegem
The correct way to do what you want in JS, ie setting a timeout afterthe page is loaded:
在JS中做你想做的正确方法,即在页面加载后设置超时:
(function(w)
{
var load = function()
{
setTimeout(postAction,60000);
if (w.removeEventListener)
{//remove listeners, to avoid leak...
return w.removeEventListener('load',load,false);
}
return w.attachEvent('onload',load);
};
if (w.addEventListener)
{
return w.addEventListener('load',load,false);
}
return w.attachEvent('onload',load);
}(this));
Instead of window.onload = function(){setTimeout(postAction,60000);};
, which will work, too, but cause a mem-leak in IE <9. That's just for completeness' sake
Anyway, the key line here is setTimeout(postAction,60000);
而不是window.onload = function(){setTimeout(postAction,60000);};
, 也可以工作,但会导致 IE <9 中的内存泄漏。这只是为了完整起见
无论如何,这里的关键是setTimeout(postAction,60000);
Update
After seeing the code you're using, this is the easiest fix:
更新
看到您正在使用的代码后,这是最简单的修复方法:
<body onLoad="setTimeout(function(){ return postAction('news.reads', 'article');}, 60000);">
回答by Mike Valenty
You need to wrap postAction
in a function to defer execution:
您需要包装postAction
在一个函数中以推迟执行:
setTimeout(function() { postAction('news.reads', 'article'); }, 60000);
You are actually executing postAction
immediately, your code is equivalent to:
您实际上是在postAction
立即执行,您的代码相当于:
var result = postAction('news.reads', 'article');
setTimeout(result, 60000);
回答by ChristopheCVB
Are you using setTimeout
like :
你使用setTimeout
像:
setTimeout(function(){alert("OK");}, 1000 * 60); // alert "OK" in 60s
回答by Martin
<script>
function doSomeJavascript() {
// javascript code goes here
alert('5 secs is up!');
}
// calls function doSomeJavascript() 5 secs after page load
var interval = setInterval(doSomeJavascript, 5000);
setTimeout(function() {
window.clearInterval(interval);
}, 5000);
</script>