Javascript:只运行一次 setInterval
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14507718/
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: Run setInterval only once
提问by Homie
Possible Duplicate:
setInterval - How to fire only once?
可能的重复:
setInterval - 如何只触发一次?
I would like to run the following code only once, so after 2 seconds it will change the iframe's src, but won't try to do it again and again.
我只想运行以下代码一次,因此 2 秒后它将更改 iframe 的 src,但不会一次又一次地尝试这样做。
<script type="text/javascript">
setInterval(function () {document.getElementById('iframe').src = "http://www.y.com";}, 2000);
</script>
回答by SLaks
You're looking for setTimeout(), which does exactly that.
您正在寻找setTimeout(),它正是这样做的。
回答by Jani Hyyti?inen
yep...
是的...
window.setTimeout(function(){
// code to run after 5 seconds...
}, 5000);
or by taking your method to outer context
或者通过将您的方法用于外部上下文
function myMethod(){
// code to run after 5 seconds...
};
window.setTimeout(myMethod, 5000);
The latter is useful if you have a method you don't plan to execute ONLY wit that timeout.
如果您有一个不打算仅在超时时执行的方法,则后者很有用。
回答by Erick Ribeiro
Use setTimeout, you can see more details in Mozilla site.
使用setTimeout,您可以在 Mozilla 站点中查看更多详细信息。

