简体   繁体   中英

I don't quite understand setTimeout and threading in javascript

I found an article in Events and timing in-depth , there is an example in this article:

function run() {
  var div = document.getElementsByTagName('div')[0]
  for(var i=0xA00000;i<0xFFFFFF;i++) {
    div.style.backgroundColor = '#'+i.toString(16)
  }
}

which says:

In most browsers, you see nothing until the script finishes, or until the browser pauses it with a message that 'a script is running too long'.

which means I can't see animation while these code is executing.

But why?I don't quite understand this, is the code execute too fast? Or the render job is done after execute the code?

and why add a setTimeout could show the animate?

While the run() function is executing the browser doesn't update the page. It waits until the function has completed executing. However with setTimeout it runs in increments - The browser updates the page for/after each run.

The summary on the link in your question explains it well :

Most browsers use single thread for UI and JavaScript, which is blocked by synchronous calls. So, JavaScript execution blocks the rendering.

Events are processed asynchronously with the exception of DOM events.

The setTimeout(..,0) trick is very useful. It allows to:

Let the browser render current changes. Evade the “script is running too long” warning. Change the execution flow. Opera is special in many places when it comes to timeouts and threading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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