0

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!

  • 7
    No, `repeat` is *not* the number of times the timer fired. It's just a number that *identifies* the timer in the system. Each browser manages the timer identifiers differently, but the purpose is the same. – Pointy Jan 31 '19 at 16:46
  • 1
    https://stackoverflow.com/questions/729921/settimeout-or-setinterval – lucifer63 Jan 31 '19 at 16:47
  • 1
    Just think about this: if `repeat` would be the amount of time the interval ran, how `clearInterval()` will use that to stop the running interval? – Shidersz Jan 31 '19 at 16:50
  • Thanks so much, guys! – Sylvan Hughes Jan 31 '19 at 16:56

1 Answers1

2

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.

Euan Smith
  • 2,102
  • 1
  • 16
  • 26