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
303 views
in Technique[技术] by (71.8m points)

javascript - Call setTimeout without delay

Quite often see in JavaScript libraries code like this:

setTimeout(function() {
    ...
}, 0);

I would like to know why use such a wrapper code.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Very simplified:

Browsers are single threaded and this single thread (The UI thread) is shared between the rendering engine and the js engine.

If the thing you want to do takes alot of time (we talking cycles here but still) it could halt (paus) the rendering (flow and paint).

In browsers there also exists "The bucket" where all events are first put in wait for the UI thread to be done with whatever it′s doing. As soon as the thread is done it looks in the bucket and picks the task first in line.

Using setTimeout you create a new task in the bucket after the delay and let the thread deal with it as soon as it′s available for more work.

A story:

After 0 ms delay create a new task of the function and put it in the bucket. At that exact moment the UI thread is busy doing something else, and there is another tasks in the bucket already. After 6ms the thread is available and gets the task infront of yours, good, you′re next. But what? That was one huge thing! It has been like foreeeeeever (30ms)!!

At last, now the thread is done with that and comes and gets your task.

Most browsers have a minimum delay that is more then 0 so putting 0 as delay means: Put this task in the basket ASAP. But telling the UA to put it in the bucket ASAP is no guarantee it will execute at that moment. The bucket is like the post office, it could be that there is a long queue of other tasks. Post offices are also single threaded with only one person helping all the task... sorry customers with their tasks. Your task has to get in the line as everyone else.

If the browser doesn′t implement its own ticker, it uses the tick cycles of the OS. Older browsers had minimum delays between 10-15ms. HTML5 specifies that if delay is less then 4ms the UA should increase it to 4ms. This is said to be consistent across browsers released in 2010 and onward.

See How JavaScript Timers Work by John Resig for more detail.

Edit: Also see What the heck is the event loop anyway? by Philip Roberts from JSConf EU 2014. This is mandatory viewing for all people touching front-end code.


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

...