简体   繁体   中英

I want to write one timer program that exits after 10 seconds in node js. But i am getting continuos output after 10. please correct my code

var i=0;

var myTimer=function(){

i++;
console.log(i);

};

console.log("Timer starts \n");
setInterval(myTimer,1000);


setTimeout(function(){

console.log(" Hey! exiting the timer after 10 seconds");

clearInterval(myTimer);
},10*1000);

You should call the clearInterval() on the setInterval() reference, not on the function called on each interval. It should look like this:

var function = function(){};
var intervalFunc = setInterval(function,1000);
clearInterval(intervalFunc);

As explained here .

UPDATE

As vivek doshi explained in more detail, in Your case You only need to add a reference to the timer and clear it properly:

var timer = setInterval(myTimer,1000);
clearInterval(timer);

Here is the answer:

You need to assign the setInterval to a variable ,which can be clear with clearInterval

Only change in your code is this 2 lines :

var timer = setInterval(myTimer,1000);
clearInterval(timer);

 var i=0; var myTimer=function(){ i++; console.log(i); }; console.log("Timer starts \\n"); var timer = setInterval(myTimer,1000); setTimeout(function(){ console.log(" Hey! exiting the timer after 10 seconds"); clearInterval(timer); },10*1000); 

Adding to the previous answer, setTimeout() is actually pushing your function to be executed in the Event Queue. The time value passed is a minimum guarantee that it will execute after 10 seconds. However, if the execution thread is still not done and, there are other pending tasks in the queue, this 10 seconds delay cannot relied upon as, it can pushed further by unexecuted code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM