简体   繁体   中英

Can someone explain how the setInterval counter works?

I created a var for a setInterval so I can stop it with clearInterval as such:

var repeat = setInterval(sayHello, 2000); 
function sayHello() { 
    alert("Hello"); 
}

and here is the clearInterval:

clearInterval(repeat)

Now, in Firefox, once I ran this bit, if I want to know the value of "repeat", it returns the amount of time the interval ran. However, in Chrome, no matter how many times it ran, it always returns 1. Unless, I do the entire procedure over, it then return 2. It basically increments the instances as opposed to interval occurrences.

Anyone able to shed some light on this, how it works, and why...greatly appreciated!

All that is guaranteed is that setInterval will return a handle which can then be used by clearInterval . Other than that it is entirely up to the browser what that handle is and how it is used. Even if it seems to provide some information in one particular browser, that should not be relied on in any way as it will be subject to change.

To quote MDN :

The returned intervalID is a numeric, non-zero value which identifies the timer created by the call to setInterval(); this value can be passed to WindowOrWorkerGlobalScope.clearInterval() to cancel the timeout.

Don't expect it, or rely on it, to be anything else.

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