I have a problem understanding the way in which setInterval
and clearInterval
work in JavaScript.
I have read different articles on these two functions but I am still confused.
Given the fact that JavaScript is single thread
then when we call test=setInterval(function(){}, t)
we will schedule our function to be executed every t
miliseconds. Unless we clearInterval(test)
.
clearInterval
we cancle
the setInterval
which is already in the queue of JavaScript?setInterval
several times but clearInterval
only once?clearInterval
in setInterval
?What does that mean? Does it mean that by clearInterval we cancle the setInterval which is already in the queue of JavaScript?
Yes.
What would happen if we setInterval several times but clearInterval only once?
Each setInterval
returns a handle that you can use with clearInterval
to stop that specific timer. Each timer is handled individually.
Can we clearInterval in setInterval?
Yes.
How JavaScript handles the scheduled process?
Pretty much like any other event. An event is triggered at an interval, and the event handler calls the callback function that you specify. If some script is running when the event is triggered, then the event will be handled when the control is returned to the browser.