1

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>
novoa
  • 129
  • 1
  • 2
  • 13

2 Answers2

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);
VisioN
  • 143,310
  • 32
  • 282
  • 281
0

use like this:

var myvar;

function myStartFunction()
{
    myvar=setInterval(function(){blink()},300);
}
function myStopFunction()
{
clearInterval(myvar);
}
Amrendra
  • 2,019
  • 2
  • 18
  • 36