Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js crashes when using long interval in setinterval

function createSasTokenTimer() {         console.log("Hello"); }  setInterval(createSasTokenTimer, 3000000); 

I run this code and after 50 minutes I get the following error:

Hello timers.js:265     callback.apply(this, args);             ^ TypeError: Cannot read property 'apply' of undefined      at wrapper [as _onTimeout] (timers.js:265:13)     at Timer.listOnTimeout (timers.js:110:15) 

When the interval time is shorter (2000000 for example), everything works fine.

Is this a bug in Node.js?


Update:

OS: Windows, Node.js version: 0.12.4

When I run only the code above it works fine, but it does break when it's inside my application, I can't point to which part of my code breaks it as it's very lengthy and nothing looks "suspicious". Anyway, when the interval is shorter it works as I wrote.

like image 217
janiv Avatar asked Jul 15 '15 07:07

janiv


People also ask

Why you should not use setInterval?

In case of time intensive synchronous operations, setTimeInterval may break the rhythm. Also, if any error occurs in setInterval code block, it will not stop execution but keeps on running faulty code. Not to mention they need a clearInterval function to stop it.

Is setInterval better than setTimeout?

setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.

Can I use setInterval in node JS?

What is the use of setInterval() method in Node. js ? The setInterval() method helps us to repeatedly execute a function after a fixed delay. It returns a unique interval ID which can later be used by the clearInterval() method which stops further repeated execution of the function.

Does setInterval affect performance?

Not appreciably. You'd have to be doing something extremely heavy in each interval for it to affect performance, and that would be true without setInterval involved at all.


1 Answers

Instead of calling the Function Directly give it inside a callback.

function createSasTokenTimer() {       console.log("Hello"); }  setInterval(function(){  createSasTokenTimer(); }, 3000000); 

Using this method, you are passing an anonymous function to setInterval. It will call this function once per interval, which is 3000000 miliseconds in this example.

For now, you can probably just use this code. For further understanding, I suggest researching anonymous functions and closures.

Hope this helps.

like image 196
SUNDARRAJAN K Avatar answered Sep 24 '22 23:09

SUNDARRAJAN K