0
var max = setTimeout(";");
for (var i=1; i< max; i++) clearTimeout(i);

I'm found the code in stack overflow can to clear all setTimeout events,

but how to understand var max = setTimeout(";");? What mean is it?

Here is original question => How to stop all timeouts and intervals using javascript?

Thank you!

  • Can you link to the original question? There may be some context. – freedomn-m Jan 06 '22 at 14:20
  • 1
    It's not guaranteed, as stated on MDN page *However, different objects use separate pools of IDs.* – freedomn-m Jan 06 '22 at 14:21
  • 2
    Looks like a neat trick, but I wouldn't recommend that anybody ever rely on this in place of managing timeouts/intervals explicitly. This could be useful for debugging purposes, or perhaps for tinkering with another page's code/functionality (like trying to hack Cookie Clicker or something of that nature), but this certainly shouldn't be considered production-stable. – David Jan 06 '22 at 14:26

2 Answers2

2

setTimeout returns a numeric ID which can be used to clear the timeout.

Creating a new timeout creates a new ID.

This code assumes that IDs will always be issued in sequential order (although I'm not aware of any implementation which doesn't).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

It simply creates empty timeout. And since setTimeout returns it's reference as incremented value, that way you can tell how much timeouts there is on page

Justinas
  • 41,402
  • 5
  • 66
  • 96
  • I appreciate for your kindness – ononokierii Jan 06 '22 at 14:24
  • 1
    The HTML specification only specifies that the ID should be a number greater than zero. It does _not_ specify that consecutive calls to `setTimeout()` should return incremental values. As such, the implementation in question is depending on a browser's implementation, and may not work as expected. – Oskar Grosser Jan 06 '22 at 18:09
  • 1
    @OskarGrosser I'm not aware of implementations that don't do incremental IDs. With that said, you are still correct - that's not something that should be relied on. A fictional example might be that the browser partitions the IDs based on some criteria and only hands over timer IDs 1-1000 to some code but another would be getting 1001-1999. So the first piece of code wouldn't be able to clear all of them using the technique in the OP. The browser might also be reusing old IDs or hand them over in non-sequential fashion. – VLAZ Jan 07 '22 at 13:05