简体   繁体   English

您如何在控制台中终止无限循环(`setInterval`)?

[英]How would you terminate an infinite loop (`setInterval`) in the console?

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. 下图中有6个重复。

在此处输入图片说明

Is there a key combination you could press or command you could type to stop the infinite loop in the console? 您是否可以按某个键或键入命令以停止控制台中的无限循环?

This is your best bet that I know of. 我知道这是您最好的选择。

var interval = setInterval(() => console.log("hello, world"), 2000);
clearInterval(interval);

To kill intervals, you need a handle to them to pass to clearInterval() . 要取消间隔,您需要一个句柄以传递给clearInterval() In your image, after you execute setInterval() , you can see the handle is returned to the console as 4491 . 在您的映像中,执行setInterval() ,您可以看到该句柄以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: 另外(更好),您应该将该句柄return分配给变量,以便可以通过编程将其杀死:

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. 句柄是一个int64数字,因此它可能很大,但是对于几乎所有应用程序来说,它都会很小,因为句柄是递增的。 Note that this method could break other packages that rely on intervals. 请注意,此方法可能会破坏依赖间隔的其他程序包。

for (var i = 1; i < 9999; i++) clearInterval(i);

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. 但是,这将暂停页面上的所有JS,而不仅仅是您的时间间隔。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM