为什么setTimeout不取消我的循环? [英] Why isn't setTimeout cancelling my loop?

查看:128
本文介绍了为什么setTimeout不取消我的循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道一个JavaScript while语句(在Chrome的控制台中)可以在一毫秒内递增一个变量的次数,因此我迅速将此代码段直接写到了控制台中:

I wondered how many times can a JavaScript while statement (in Chrome's console) can increment a variable in a millisecond, so I quickly wrote this snippet directly into console:

var run = true, i = 0;
setTimeout(function(){ run = false; }, 1);
while(run){ i++; }

问题在于它可以永远运行.
为什么会发生这种情况,我该如何解决?

The problem is that it runs forever.
Why is this happening, and how can I solve it?

推荐答案

这又回到了JavaScript 1 的单线程性质.发生的事情几乎是这样的:

This comes back to the one-threaded nature of JavaScript1. What happens is pretty much this:

  1. 已分配变量.
  2. 您计划一个功能来设置run = false.计划在当前功能运行后 之后运行(或当前处于活动状态的其他任何功能).
  3. 您将陷入无限循环,并停留在当前函数之内.
  4. 无限循环(从不)后,将执行setTimeout()回调并run=false.
  1. Your variables are assigned.
  2. You schedule a function, to set run = false. This is scheduled to be run after the current function is run (or whatever else is currently active).
  3. You have your endless loop and stay inside the current function.
  4. After your endless loop (never), the setTimeout() callback will be executed and run=false.

如您所见,setTimeout()方法在这里行不通.您可以通过检查while条件下的时间来解决此问题,但这会干扰您的实际测量.

As you can see, a setTimeout() approach wont work here. You might work around that by checking the time in the while condition, but this will tamper with your actual measurement.

1 至少出于更实际的目的,您可以将其视为单线程.实际上,存在一个所谓的事件循环".在该循环中,所有函数将排队等待执行.如果将新功能排队,则将其放在该队列内的相应位置. 当前功能完成后,引擎从队列中获取下一个功能(关于由例如setTimeout()引入的计时,并执行该功能.
结果,在每个时间点仅执行一个函数,从而使执行几乎是单线程的.事件有一些例外情况,下面的链接中对此进行了讨论.

1 At least for more practical purposes you can see it as single-threaded. Actually there is an so called "event-loop". In that loop all functions get queued until they are executed. If you queue up a new function, it is put at the respective position inside that queue. After the current function has finished, the engine takes the next function from the queue (with respect to timings as introduced, e.g., by setTimeout() and executes it.
As a result at every point in time just one function is executed, thus making the execution pretty much single threaded. There are some exceptions for events, which are discussed in the link below.

供参考:

在这里详细解释了类似的情况

Here a similar scenario was explained in more detail

https://stackoverflow.com/a/2734311/1169798

关于何时可以将JS视为单线程以及何时不将其视为更深入的描述.

A more in-depth description on when JS can be seen as single-threaded and when not.

这篇关于为什么setTimeout不取消我的循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆