Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript setTimeout setInterval within one function

I think I might be overtired but I cannot for the life of me make sense of this, and I think it's due to a lack of knowledge of javascript

var itv=function(){
 return setInterval(function(){
  sys.puts('interval');
 }, 1000);
}
var tout=function(itv){
 return setTimeout(function(){
  sys.puts('timeout');
  clearInterval(itv);
 }, 5500);
}

With these two functions I can call

a=tout(itv());

and get a looping timer to run for 5.5 seconds and then exit, essentially.



By my logic, this should work but it simply is not

var dotime=function(){
 return setTimeout(function(){
  clearInterval(function(){
   return setInterval(function(){
    sys.puts("interval");
   }, 1000);
  });
 }, 5500);
}

any insight in this matter would be appreciated.

like image 449
dagoof Avatar asked Mar 17 '10 17:03

dagoof


1 Answers

it cannot work because because your setInterval will be called AFTER the timeout! your original approach is correct and you can still wrap this into single function:

var dotime=function(){
  var iv = setInterval(function(){
    sys.puts("interval");
  }, 1000);
  return setTimeout(function(){
    clearInterval(iv);
  }, 5500);
};
like image 148
skrat Avatar answered Nov 15 '22 13:11

skrat