The magical settimeout 0 of JS asynchronous execution

Source: Internet
Author: User

  Recently encountered some problems in the work, is roughly about the JS implementation problem. Some strange bugs were caused by the failure to understand the order of execution. So here's some knowledge about asynchronous execution (tip of the iceberg) ...

  We all know that JS is single-threaded, execution is sequential, in the sequence of business logic of course no problem. If you encounter business logic that can be executed concurrently, then the queue is very low, so it needs to be executed asynchronously!

1. What is async?

SetTimeout (function() {Console.log (0);},0) console.log (1);
// Print first 1 // re-print 0

  Some restaurants, for example, you go to dinner. Need to pre-order ( Asynchronous Code Execution ), and so on other people eat ( synchronization code is finished ) you can go, so when others eat ( synchronous Code Execution ) You can do other things , wait for the others to finish (the synchronization code is finished ) someone will tell you, so you can go ( start executing asynchronous code "settimeout/setinterval/event handler/ajax callback ..." ).

We go back to that section of settimeout body, it works like this, when you define settimeout that moment (regardless of time is not 0), JS will not go directly to execute this code, but throw it into an event queue, The code in the event queue is not executed until all the synchronization tasks on the page have been completed . What is synchronization, executed in code order, is played in order like in the music player.

2, the magical setTimeout 0

 <!  DOCTYPE html> ( function   () { function  Span style= "COLOR: #000000" > $ (id) { return    document.getElementById (ID); } $ ( ' input '). onkeypress = function   () {$ (  span> ' preview '). InnerHTML = this  .value; }})(); </script>

the intent of this keypress function is to listen to the user input string and display it in its entirety, but it is strange that the last string will never be displayed:

  

  The focus is on using settimeout to solve:

function () {      setTimeout() {$ (' preview '). InnerHTML = $ (' input '). value;},0);   } 

 Okay, The problem is solved, first look back to see how the problem arises?

In the code, the events we use are keypress, and when the KeyPress event occurs, the state of the DOM element has not changed, the state of the DOM element has changed after the KeyPress event, and the desired result is achieved by settimeout 0 delay execution. Of course, not settimeout 0, directly with onkeyup can also.

  But SetTimeout's little problem is that time is imprecise:

<! DOCTYPE html>(function(){  functionget (ID) {returndocument.getElementById (ID); }  functionlog (a) {Console.log (a)} window.onload=function() {Get (' Makeinput '). onmousedown=function(){      varinput = document.createelement (' input '); Input.setattribute (' Type ', ' text '); Input.setattribute (' Value ', ' test1 '); Get (' Inpwrapper '). appendchild (input); Input.onfocus=function(){//binding the focus event to the generated inputLog ("Iptfocus");      } input.focus (); Log ("Down"); } Get (' Makeinput '). onfocus =function() {log ("Btnfocus"); } Get (' Makeinput '). onclick =function() {log ("Click"); } Get (' Makeinput '). onmouseup=function() {log ("Up"); }   }})();</script>//Print Iptfocus//Print down//print Btnfocus result in new input no focus of the real killer//Print up//Print Click

  Will Input.focus (); Change to SetTimeout (function () {input.focus ();},0); The results are:

// Print down //  //  print Iptfocus  ghosts know why they run to this. Execute //  printup//  Print Click 

  

Understand the JS asynchronous execution and settimeout 0 work principle, can better facilitate our work to solve the bug ...

The magical settimeout 0 of JS asynchronous execution

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.