Does “setTimeout(functon(){//do stuff},0)” cause a minuscule execution delay for it's contained function?

末鹿安然 提交于 2019-12-06 06:28:45

JavaScript is singled-threaded and event-based. setTimeout() immediately creates a new event that needs to be processed, but the current "event" (function/code) must be finished, first.

Excerpt from Events and timing in-depth:

When setTimeout gets 0 as the last argument, it attempts to execute the func as soon as possible.

The execution of func goes to the Event queue on the nearest timer tick. Note, that’s not immediately. No actions are performed until the next tick.

Other detailed explanations:


Note: I often use this setTimeout(func, 0) "trick" to execute code that must be run after a DOM manipulation or the current function is completed.

I think that you do not anderstand the behaviour of setTimeout(function (){}, 0);

Let's analyse the code step by step. Code 1:

  1. Creates a .box element and append in the DOM.
  2. Search for .box elements in the DOM.
  3. Handles the click event to that elements.

If you clic on the .box element then you will get execute the click callback.

The second code:

  1. You prepare a function to be executed in the future. This future will be in, at least, 0 ms, but still in the future. It is an asynchronous execution
  2. Search for .box elements in the DOM, but there aren't elements.
  3. Handles the click event to that elements, but there aren't elements.
  4. After the execution flux, the setTimeout function callback is executed. Then you create your .box element.

Unfortunately, you didn't applied the callback to any element because it was not created during the click handling.

It causes the function to be executed asynchronously.

It executes instantly but asynchronously, that means that it doesn't follow the normal flow, so It could be executed after or before the next function, you don't have control over that anymore.

What setTimeout(someFunction, timeInMS) means is that JavaScript will call someFunction AT LEAST timeInMS milliseconds in the future.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!