Discussion on Javascript thread and timing mechanism

  • 2020-06-22 23:52:00
  • OfStack

Use of setTimeout and setInterval

The second parameter of setTimeout and setInterval is defined in the Javascript api document to mean how many milliseconds after the callback function is executed and how many milliseconds after the callback function is executed, respectively. But as we gained experience, we discovered that this was not the case.

Such as


div.onclick=function(){
  setTimeout(function(){
     document.getElementById('input').focus(); 
  },0);
}

Can't explain, immediately implement immediately bai, why also set a regular circle.

Another day you write the following piece of code


setTimeout(function(){while(true){}},100);
setTimeout(function(){alert(' hello ');},200);

The first line of code loops so that line 2 alert never appears. Why?

Single thread or multi-thread #63;
Originally, the Javascript engine was single-threaded, and the browser had only one thread running the JavaScript program. Because of the single-thread design, the complex multi-thread synchronization problem is eliminated.

When a timer is set, the browser inserts your specified callbacks into the task sequence after the timer is set, rather than executing immediately. If the timing time is set to 0, it means that the sequence of tasks will be inserted immediately, rather than executed immediately. You will still wait until the tasks in the queue finish executing and your turn to execute.

So this code pops out a 2, then a 1


setTimeout(function(){
  alert(1);
},0);
alert(2);

So what's the practical use of this? Consider the following example


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>setTimeout 0</title>
  </head>
  <body>
     Enter characters, but the content is not displayed in real time <input type="text" onkeydown="show(this.value)"/> <br/>
     Input character, content can be displayed in real time <input type="text" onkeydown="var self=this;setTimeout(function(){show(self.value)},0)"/>
    <div></div>
    <script>
      function show(val){
        document.getElementsByTagName("div")[0].innerHTML=val;
      }
    </script>
  </body>
</html>

In this example, the js engine needs to execute the keydown event handler and then update the value value of the input field. When the event handler executes, the task of updating value can only enter the queue to wait, so the updated value value cannot be obtained when the keydown event executes. But with setTimeout we queue the fetch of value and perform it after updating value, so the content is displayed in real time.

Return to the following code:


setTimeout(function(){
  //do something...
   setTimeout(arguments.callee,10);
},10);

setInterval(function(){
  //do something...
},10);

These two pieces of code look exactly the same, don't they? In fact, there is a difference. The setTimeout in the callback function in the first paragraph is the new timing set after the execution of the js engine. It is assumed that there is a time interval from the completion of the last callback to the beginning of the next callback > =10ms, the last 1 code < = 10 ms.

Speaking of which, is XMLHttpRequest really asynchronous? Yes, the request is asynchronous, but it is a new thread opened by the browser. When the state of the request changes, if callbacks have been previously set, the asynchronous thread puts the state change event into the js engine processing queue for processing. The js engine always executes the functions set by onreadystatechange single-threaded when the task is processed.

This is the end of this article, I hope you enjoy it.


Related articles: