Henrique Van Klaveren Henrique Van Klaveren -4 years ago 104
Javascript Question

node/js stop the function before running it again

I have a function running at each time interval, I need to simply stop the function before running it again.

Something similar to the code below.

var interval = 1000*60*3.14159;

setInterval( function(){
setTimeout( myfunction(), interval )
}, interval );

Answer Source

Your code, especially together with the requirement, doesn't make sense. First, you need to pass a reference to a function to setTimeout instead of executing it directly,

setTimeout(myfunction, 1000);

Otherwise, setTimeout has no effect at all and the function will just be executed without a timeout.

Now if we fix this error, what we have is a interval that is the same for setInterval and for setTimeout. If you want to stop the execution of the function we've passed to setTimeout everytime the setInterval ticks, your setTimeout will be interrupted and never executed because of the same interval you've specified. The next tick will stop the function before it did a thing.

See this example - notice that nothing happens:

var interval = 1000;

setInterval( function(){
  var i = setTimeout( myfunction, interval )
}, interval );

function myfunction() {
	console.log("you'll never see me"); 

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download