2

For instance, we could run

setInterval(function(){console.log("Hello, SO!")}, 2000);

Hello, SO! gets repeated every two seconds in the terminal. There are 6 repeats in the picture below.

enter image description here

Is there a key combination you could press or command you could type to stop the infinite loop in the console?

Maximilian Burszley
  • 18,243
  • 4
  • 34
  • 63
Clone
  • 3,378
  • 11
  • 25
  • 41
  • 1
    If you have no reference to the interval, your best bet would be to hit `F5` to refresh the page, or to clear every possible interval (since they are given numerical IDs by the browser): `for (var i = 1; i < 99999; i++) clearInterval(i)` https://stackoverflow.com/a/6843415/1913729 . **Or** just use the ID you see in your console: `clearInterval(4491)` – blex May 15 '18 at 20:18
  • @blex where are handles documented? I checked mdn and it looks like the interval is a `int32`, but I couldn't find docs on the handle itself. – Maximilian Burszley May 15 '18 at 20:27
  • 1
    In the HTML Standard specification, they only refer to it as a _[user-agent-defined integer that is greater than zero](https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timer-initialisation-steps)_. In the specs implementation, they use a [`long`](https://html.spec.whatwg.org/multipage/webappapis.html#windoworworkerglobalscope) – blex May 15 '18 at 20:33
  • 1
    @blex Thanks for that. So it could potentially be a very large number, but likely not since they're incremented. – Maximilian Burszley May 15 '18 at 20:35

3 Answers3

2

This is your best bet that I know of.

var interval = setInterval(() => console.log("hello, world"), 2000);
clearInterval(interval);
ryan.wise
  • 469
  • 3
  • 9
2

To kill intervals, you need a handle to them to pass to clearInterval(). In your image, after you execute setInterval(), you can see the handle is returned to the console as 4491. In this way, you can kill it like so:

clearInterval(4491);

Alternatively (and better), you should assign that handle return to a variable so you can kill it programmatically:

let interval = setInterval(() => console.log('Hello, SO!'), 2000);
clearInterval(interval);

Edit:
You can also brute-force. The handle is an int64 number, so it could potentially be enormous, but for almost any app, it'll be small since the handles are incremented. Note that this method could break other packages that rely on intervals.

for (var i = 1; i < 9999; i++) clearInterval(i);
Maximilian Burszley
  • 18,243
  • 4
  • 34
  • 63
0

You can stop script execution on the current page using the pause button described here. This will pause all JS on the page though, not just your interval.

Nick Swope
  • 331
  • 2
  • 7