setInterval & setTimeout?

ε祈祈猫儿з 提交于 2019-12-24 17:44:13

问题


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>

回答1:


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

var interval = setInterval(blink, 300);

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



回答2:


use like this:

var myvar;

function myStartFunction()
{
    myvar=setInterval(function(){blink()},300);
}
function myStopFunction()
{
clearInterval(myvar);
}


来源:https://stackoverflow.com/questions/15292676/setinterval-settimeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!