views:

354

answers:

3

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.

+3  A: 

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);
}
Chad_K
+5  A: 

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);
};
skrat
This is definitely it. He's not creating the interval until the timeout callback executes.
Peter Bailey
Thank you for the wake up call/concise answer, don't know what I was thinking
dagoof
+1, Closure magic as it's best.
Alex Bagnolini
+1  A: 

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.

David V.