js中 setTimeout延時0毫秒的作用


轉載自:https://www.cnblogs.com/hajerbin/p/7098055.html

解決的問題:

1、代碼中改變了dom,又想在后續的代碼中操作此dom(自己不知道dom什么時候渲染就緒)。此用法對比Vue的nextTick()。

2、onkeypress等事件的觸發是有先后順序的,想在這些觸發的事件執行完之后執行。比如input的內容改變是在的onkeypress事件之后,即onkeypress中無法獲取input事件的改變,這時候可以使用setTimeout(func,0)

相關術語:

宏任務、微任務

演示代碼:

 1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
 2 <html>
 3 <head>
 4     <meta charset="utf-8">
 5     <title>setTimeout</title>
 6 
 7     <script type="text/javascript" >
 8         (function(){
 9 
10             function get(id){
11                 return document.getElementById(id);
12             }
13 
14             window.onload = function(){
15                 get('makeinput').onmousedown = function(){
16                     var input = document.createElement('input');
17                     input.setAttribute('type', 'text');
18                     input.setAttribute('value', 'test1');
19                     get('inpwrapper').appendChild(input);
20                     input.focus();
21                     input.select();
22                 }
23                 get('makeinput2').onmousedown = function(){
24                     var input = document.createElement('input');
25                     input.setAttribute('type', 'text');
26                     input.setAttribute('value', 'test1');
27                     get('inpwrapper2').appendChild(input);
28                     setTimeout(function(){
29                         input.focus();
30                         input.select();
31                     }, 0);
32                 }
33                 get('input1').onkeypress = function(){
34                     get('preview1').innerHTML = this.value;
35                 }
36                 get('input2').onkeypress = function(){
37                     setTimeout(function(){
38                         get('preview2').innerHTML = get('input2').value;
39                     },0 );
40                 }
41             }
42         })();
43 
44     </script>
45 
46 </head>
47 
48 <body>
49 <h1><code>DEMO1</code></h1>
50 <h2>1、未使用 <code>setTimeout</code>(未選中文本框內容)</h2>
51 <button id="makeinput">生成 input</button>
52 <p id="inpwrapper"></p>
53 <h2>2、使用 <code>setTimeout</code>(立即選中文本框內容)</h2>
54 <button id="makeinput2">生成 input</button></h2>
55 <p id="inpwrapper2"></p>
56 
57 --------------------------------------------------------------------------
58 <h1><code>DEMO2</code></h1>
59 <h2>1、未使用 <code>setTimeout</code>(只有輸入第二個字符時,前一個字符才顯示出來)</h2>
60 <input type="text" id="input1" value=""/><div id="preview1"></div>
61 <h2>2、使用 <code>setTimeout</code>(輸入時,字符同時顯示出來)</h2>
62 
63 <input type="text" id="input2" value=""/><div id="preview2"></div>
64 
65 </body>
66 </html>

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM