关于js的setTimeout

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>setTimeout作用解释1</title>
<script type="text/javascript" >
// bsd lisenced 2008 realazy
(function(){
  
   // document.getElementById shorthand
   function get(id){
    return document.getElementById(id);
   }
  
   window.onload = function(){
    get('makeinput').onmousedown = function(){
     var input = document.createElement('input');
     input.setAttribute('type', 'text');
     input.setAttribute('value', 'test1');
     get('inpwrapper').appendChild(input);
     input.focus();
     input.select();
    }
    get('makeinput2').onmousedown = function(){
     var input = document.createElement('input');
     input.setAttribute('type', 'text');
     input.setAttribute('value', 'test1');
     get('inpwrapper2').appendChild(input);
     setTimeout(function(){
      input.focus();
      input.select();
     }, 0);
    }

// 这个例子,onkeypress在字符出现之前触发,所以不加setTimeout拿到上一个变化。加了setTimeout拿到正在变化。
    get('input').onkeypress = function(){
      var input = this;
      setTimeout(function(){
        get('preview').innerHTML = input.value;
      },0);
      
    };
    
   }
})();
</script>
</head>
<body>
  文档更新一个线程,事件处理一个线程,浏览器处理html,css,js是单线程,处理了文档更新,没有额外线程处理事件。而setTimeout可以重新生成任务队列,所以你懂的。<br />
<h1><code>setTimeout</code></h1>
<h2>1、未使用 <code>setTimeout</code></h2>
<button id="makeinput">生成 input</button>
<p id="inpwrapper"></p>
<h2>2、使用 <code>setTimeout</code></h2>
<button id="makeinput2">生成 input</button></h2>
<p id="inpwrapper2"></p>
<h2>3、另一个例子</h2>
<p><input type="text" id="input" value=""/><span id="preview"></span></p>
<br />
<span id="preview2"></span>
</body>
</html>

 

posted @ 2013-01-05 12:21  草珊瑚  阅读(555)  评论(0编辑  收藏  举报