开发者

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(f开发者_如何学Cunction(){
  clearInterval(function(){
   return setInterval(function(){
    sys.puts("interval");
   }, 1000);
  });
 }, 5500);
}

any insight in this matter would be appreciated.


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);
};


I think the mistake you're making is that the function itv doesn't return setInterval(function(){ sys.puts('interval'); }, 1000) it executes setInterval(function(){ sys.puts('interval'); }, 1000) and than returns back an ID that setInterval generates. That ID is then passed to the clearInterval function to stop what setInterval(function(){ sys.puts('interval'); }, 1000) is doing.

Edit: An example of one function that would work.

var dotime=function(){
 // Start our interval and save the id
 var intervalId = setInterval(function(){
  // This will get executed every interval
  sys.puts("interval");
 }, 1000);

 // Start our timout function
 setTimeout(function(){
  // This will get executed when the timeout happens
  clearInterval(intervalId); // Stop the interval from happening anymore
 }, 5500);
}


This is another way to write your version, you see that you pass a function to clearInterval, where you should have passed it a timer id.

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

To make it work you shoud call the function :

  clearInterval(f());

Or, using your version :

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

Disclaimer : I didn't test this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜