Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

javascript - Why isn't setTimeout cancelling my loop?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

  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.

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 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.


For reference:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...