This is the Mozilla Developer Network example of window.setInterval
var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
var intervalID = window.setInterval(code, delay);
(which can be found here: https://developer.mozilla.org/en/DOM/window.setInterval)
I’m more used to compiled Java programming of these types of algorithms so my question is:
How does intervalID work? It seems that there is some kind of recursive function going on there behind the scenes but that’s a complete guess – how is it structured and is that structure (presumably quite large) stored as intervalID, waiting for clearInterval(intervalID)?
I’m just going to assume that you want to know how it works in the Firefox browser (each browser has its own implementation of the same method). The implementation can be found in nsGlobalWindow::SetTimeoutOrInterval() and it is actually pretty straightforward. Each window has a list of outstanding timeouts and when you call
window.setInterval()a new timeout structure is created and added to that list. The timeout structure contains a reference to the timer object that will notify the window whenever the callback needs to called. And it has anmPublicIdmember that is simply a number – it gets incremented for each new timeout created and is returned bysetInterval(). When you callclearInterval()it will look up a timeout with matching ID in the list and remove it.