转载自: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>