Symbolwdd Symbolwdd - 5 months ago 13
jQuery Question

Javascript - Dynamically changing interval value of setTimeout/setInterval

Can anyone please explain this code?

var checkinterval = 1;
var myFunction = function(){
clearInterval(Interval2);
console.log(checkinterval++);
setInterval(myFunction, 5000);
}
var Interval2 = setInterval(myFunction, 1000);


This code is calling a function within its own definition. i.e. inside myFunction, there is setInterval(myFunction, 5000) which is calling the function inside its own definition. That does not make sense.

Similarly in clearInterval(Interval2), the variable Interval2 is being called before its own definition.

I am sorry but I am just a newbie with these timers. Can someone please elaborate these bits of lines of code?

Answer

From my understanding:

When you stored the function to the 'myFunction' variable, it is not executed immediately. They are simply stored for later use when you actually do invoke them.

This happens in the following line:

var Interval2 = setInterval(myFunction, 1000);

What this does is it invokes myFunction every 1 second. In your case, however, it executes myFunction once only, because in myFunction the

clearInterval(Interval2)

line would have then cleared the timer assigned to the Interval2 variable.

But the code does not just stop there. In myFunction, this line:

setInterval(myFunction, 5000);

would call myFunction every 5 seconds, which increments your checkInterval by 1 and outputs it to the console. This is what causes your browser to crash, because if you think about it:

First call of myFunction: 1 instance of myFunction would be queued to run in the next 5s (lets call this A)

5s later...

A is executed, which increments checkInterval by 1, and queues ANOTHER instance of myFunction to run in 5s (call this B)

5s later...

A is executed, which increments checkInterval by 1, and queues ANOTHER instance of myFunction to run in 5s (call this C)

A is executed, which increments checkInterval by 1, and queues ANOTHER instance of myFunction to run in 5s (call this D)

5s later...

A is executed... B is executed... C is executed... D is executed...

You get the drift.

Essentially what this code does is double the number of 'myFunction's to be executed every 5s. Eventually there would be so many of them to run, your browser would naturally be unable to handle the load.

Hope my explanation did not confuse you. I'll try to clarify any doubts you might have.

Comments