JavaScript setTimeout setInterval within a single function

I think I could overdo it, but I can’t let life understand me about it, and I think this is due to ignorance 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 cycle timer to start for 5.5 seconds, and then exit essentially.



By my logic, this should work, but it just doesn't

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

Any understanding of this issue would be appreciated.

+5
source share
3 answers

it cannot work because yours setIntervalwill be called AFTER a timeout! your original approach is correct, and you can still wrap it in one function:

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

, , , , itv setInterval(function(){ sys.puts('interval'); }, 1000), setInterval(function(){ sys.puts('interval'); }, 1000) , setInterval. clearInterval, setInterval(function(){ sys.puts('interval'); }, 1000).

: , .

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

, , clearInterval, .

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

, :

  clearInterval(f());

Or using your version:

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

Disclaimer: I have not tested this.

+1
source

All Articles