setInterval &设置超时? [英] setInterval & setTimeout?

查看:92
本文介绍了setInterval &设置超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 x 秒后停止我的 javascript,我看到函数是 setTimeout,我试图将它添加到我的代码中但没有成功,这是更好的方法吗?谢谢你的帮助 !

I want to stop my javascript after x seconds, I saw that the function is setTimeout, I tried to add that to my code but no succes, is this the better way to do this? Thanks for your help !

<html>
<head>
<script type="text/javascript">
   function blink(){
state = document.getElementsByTagName('img')[0].style.visibility;
if(state == 'hidden'){
    newState = 'visible';
}else if(state == 'visible'){
    newState = 'hidden';
}
document.getElementsByTagName('img')[0].style.visibility = newState;
    }
   setInterval('blink();', 300);
</script>
</head>
<body>
<img src="http://ww1.prweb.com/prfiles/2011/10/12/8875514/star_white.jpg" style="visibility:hidden">  
</body> 
</html>

推荐答案

在变量中初始化您的间隔,并在 X(此处为 2)秒后清除它:

Initialize your interval in a variable and clear it after X (here 2) seconds:

var interval = setInterval(blink, 300);

setTimeout(function() {
    clearInterval(interval);
}, 2000);

这篇关于setInterval &amp;设置超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆