settimeout = 0 的 问题

来源:互联网 发布:程序员入门培训 编辑:程序博客网 时间:2024/06/07 05:58


大致就是说,单线程 
settimeout=0的时候,浏览器找合适的时间执行,不造成阻塞





转载注明出处^_^:  http://www.cnblogs.com/suspiderweb/

起因源于一道前端笔试题:

var fuc = [1,2,3];for(var i in fuc){  setTimeout(function(){console.log(fuc[i])},0);  console.log(fuc[i]);}

 

问:控制台会如何打印?

chrome打印结果如下:

 

虽然setTimeout函数在每次循环的开始就调用了,但是却被放到循环结束才执行,循环结束,i=3,接连打印了3次3。

这里涉及到javascript单线程执行的问题:javascript在浏览器中是单线程执行的,必须在完成当前任务后才执行队列中的下一个任务。

另外,对于javascript还维护着一个setTimeout队列,未执行的setTimeout任务就按出现的顺序放到setTimeout队列,等待普通的任务队列中的任务执行完才开始按顺序执行积累在setTimeout中的任务。

所以在这个问题里,会先打印1 2 3,而将setTimeout任务放到setTimeout任务队列,等循环中的打印任务执行完了,才开始执行setTimeout队列中的函数,所以在最后会接着打印3次3。

 

由此,可以知道虽然设置为0秒后执行任务,实际上是大于0秒才执行的。可是这有什么用呢?

用处就在于我们可以改变任务的执行顺序!因为浏览器会在执行完当前任务队列中的任务,再执行setTimeout队列中积累的的任务。

通过设置任务在延迟到0s后执行,就能改变任务执行的先后顺序,延迟该任务发生,使之异步执行。

 

网上有个比较有意思的案例:

复制代码
<!DOCTYPE html><html lang="zh-cmn-Hans">  <head>    <title></title>    <meta charset="utf-8">  </head>  <body>  <p>    <input type="text" id="input" value=""/>    <span id="preview"></span>  </p>  </body>   <script type="text/javascript">(function(){  function $(id){    return document.getElementById(id);  }  $('input').onkeypress = function(){    $('preview').innerHTML = this.value;  }})();
</script></html>
 
复制代码

 

这个keypress函数原意是监听到用户输入字符串就将其完整的显示出来,但是奇怪的是最后一个字符串总是没能显示出来:

,

但是只要改下onkeypress函数就好:

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

将onkeypress里面的事件延迟到浏览器更新相关DOM元素的状态之后执行,这是就能显示出所有字符串了,如下:

 

setTimeout()是用来改变任务执行顺序的,难道就没有其他代替的方法了吗?答案是有的。

将监听keypress事件改为监听keyup事件,一样能达到同样的效果:

$('input').onkeyup = function(){  $('preview').innerHTML = $('input').value;}

 

这里跟key事件的执行顺序有关:

 

复制代码
(function(){  function $(id){    return document.getElementById(id);  }  function log(a){    console.log(a);  }  $('input').onkeypress = function(){    log("keypress: "+this.value);  }  $('input').onkeyup = function(){    log("keyup: "+this.value);  }  $('input').onkeydown=function(){    log("keydown: "+this.value);  }})();
复制代码

 

当用键盘输入1后,控制台打印结果如下:

也就是先执行keydown事件,再执行keypress事件,执行keypress事件之后改变dom元素的状态(这里是input的value改变了),再执行keyup。

这也解释了为什么通过监听keyup事件就能正确且及时的打印出input的值。

而keypress事件发生时,dom元素的状态还未改变,keypress事件之后dom元素的状态才发生改变,通过setTimeout延迟执行就能达到期望的结果了。

测试过chrome,firefox,ie表现一致。

 

再来看看另一个例子,稍微有些改动,来自http://blog.csdn.net/lsk_jd/article/details/6080772:

复制代码
<!DOCTYPE html><html lang="zh-cmn-Hans">  <head>    <meta name="generator" content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39">    <title></title>    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <meta charset="utf-8">    <meta name="Description" content="SUperman">    <style type="text/css">    </style>  </head>  <body>    <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>  </body>   <script type="text/javascript">(function(){  function get(id){    return document.getElementById(id);  }  function log(a){    console.log(a)  }  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();    }    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();},0);    }   }})();</script></html>
复制代码

 

该例子中,未使用setTimeout生成的input没有获得focus,而使用了setTimeout的input可以获得focus,这也是和setTimeout改变任务执行顺序有关。

可是生成的input为什么不会focus呢?是这个focus没执行吗,通过给focus绑定一个事件就可以知道事实是怎样:

复制代码
get('makeinput').onmousedown=function(){      var input = document.createElement('input');      input.setAttribute('type', 'text');      input.setAttribute('value', 'test1');      get('inpwrapper').appendChild(input);      input.onfocus=function(){    //给生成的input绑定focus事件        log("focused");      }      input.focus();    }
复制代码

 

结果发现控制台有打印"focused"的,进一步猜测未使用setTimeout生成的input获取了focus又失去focus,改下代码看看mouse事件和focus事件的执行顺序:

复制代码
    get('makeinput').onmousedown=function(){      var input = document.createElement('input');      input.setAttribute('type', 'text');      input.setAttribute('value', 'test1');      get('inpwrapper').appendChild(input);      input.onfocus=function(){        log("focused");      }      input.focus();      log("down");    }    get('makeinput').onfocus = function(){      log("focus");    }    get('makeinput').onclick = function(){     log("click");    }    get('makeinput').onmouseup=function(){      log("up");    }
复制代码


结果如下:

 

可见先执行mousedown事件,然后生成的input获得focus,接着按钮获得focus,接着执行mouseup事件,再执行click事件,和key的3个事件的执行顺序有些不同。

看到这里恍然大悟,这个生成的input确实是获得了focus,但是随之失去focus,因为按钮的mousedown事件紧跟着按钮的focus事件,被按钮夺取了focus。

将 input.focus(); 改为 setTimeout(function(){input.focus();},0);得到结果为:

 

也就是通过延迟执行input获取focus事件,最终就是生成的input获取了focus。

这样的话,通过绑定mouseup,click事件同样能使生成的input夺取按钮的focus事件,事实证明确实如此,就不贴代码上来了。

如果绑定focus事件会怎样呢?这一次,chrome和ie站在了统一战线,都是生成一个获取了focus的input,但有趣的是firefox居然生成了2个。

不过ie反应也不算正常,绑定mousedown时不使用setTimeout的输出是这样的orz:

 

 

 

也就是focus事件好像不执行了,由于没有执行按钮的focus事件,生成的input是获得focus的,也就是不需要延迟执行函数,生成的input也能获取focus。

赶紧将input.focus()注释掉,发现打印出"focused"的地方替换成了"focus",将生成input且获取focus的代码绑定到其他mouse事件和focus事件得到的结果比较复杂,就暂且不做深究,但是可以知道按钮都能执行focus事件,除了绑定mousedown事件忽略了foucs事件。

原因不详,应该是和各浏览器对focus的具体实现有差异吧。看到的朋友若知道什么原因,欢迎告知。

 

不过折腾了这么久,敢肯定setTimeout确实是实现异步执行的利器。这次对setTimeout的探讨也没有很深入,不过同时也弄清楚了key事件、mouse事件和focus事件的执行顺序。

原创粉丝点击