日期:2014-05-16  浏览次数:20319 次

JavaScript中的setTimeout和setInterval

1. 两个函数各自的意义

?

setTimeout (fu,time,args);  //过time时间自动执行fn函数,fn可以是codestr可以使函数

setInterval(fn,time)args;  //每隔time时间执行fn函数 重复循环执行
?

?

2. 在浏览器下表现的差异

?

function f(){
    var s = 'arguments.length:'+arguments.length+'; ';
    for(var i=0,n=arguments.length;i< n;i++){
        s += ' ['+i+']:'+arguments[i]+'; ';
    }
    alert(s);
}
setTimeout(f,500,"javascript","AAA")
?

? ? ? 上面这段代码在下面几个浏览器中变现并不相同:

?

ie中: ?argument.length : 0

?

? ? ? ? ff中 : argument.lenght : 3 。。。。。

?

? ? ? ?chrome中 : argument.length : 2 ?

?

? ?出现错误的原因:

?

? ? ? ? ? ?ie中: 因为ie是支持多种脚本语言,所以第三个参数是用来表明语言类型的变量

?

? ? ? ? ? ?ff中: 会有三个参数是firefox的一个bug ?他会在setTimeout函数最后添加一个参数

?

? ? ? ? ? chrome opera 等 数值正确

?

3. 如何解决ie的差异

?

? ? ? ? ? ? 对于ie中无法传递参数可以通过匿名函数解决:

?

? ? ? ? ? ? 例如:?

?

function inner(a){
                 alert(a);
           }

var str = "test";

setTimeout(function(){inner(str)},1000);
?

?

?

4. this问题

?

? ? ?setTimeout 中得函数调用的上下文是全局,就是this执行window对象。如果需要改变上下文环境可以使用apply动态传递this值。

?

5. JavaScript中的单线程性质

?? ??http://www.phpweblog.net/rainman/archive/2009/01/05/6267.html

?

?

6. setTimeout和claerTimeout在循环中的使用

?

参考文章http://www.iteye.com/topic/578308