Set setTimeout delay is the role of 0ms

       When we execute the following code, the result will pop up in the order of 3,2.

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

       This is the event loop mechanism, because js is single-threaded, event-based cycle. The setTimeout function is asynchronous, asynchronous events will join a queue, will wait until after the current mandate synchronization is complete, then perform setTimeout task queue. Therefore, by providing task execution delay 0 ms after, task execution order can be changed, the delay of the task occurs, change the priority function it calls, so that asynchronous execution.

       Example:
1. The following code is not to obtain real-time content inside the input box.

<input type="text" onkeydown="test(this.value)">  
<div></div>  
<script">  
  function test(val) {  
    document.getElementsByTagName('div')[0].innerHTML = val;  
  }  

       Can be found in every press a character, <div> can only see the content before, you could not get the current character. The results are as follows:
Here Insert Picture Description

2. The use setTimeout delay is 0, we get the value of the operation in the queue, the value placed after the update value.

<input type="text" onkeydown="var that=this; setTimeout(function() {test(that.value)}, 0)">  
<div></div>  
<script">  
  function test(val) {  
    document.getElementsByTagName('div')[0].innerHTML = val;  
  } 

       Real-time display of the contents of the input results are as follows:
Here Insert Picture Description

Published 62 original articles · won praise 229 · views 40000 +

Guess you like

Origin blog.csdn.net/weixin_42881768/article/details/104793703