当前位置: 代码迷 >> Web前端 >> [转]setTimeout 与setInterval 在不同浏览器下运行的差异
  详细解决方案

[转]setTimeout 与setInterval 在不同浏览器下运行的差异

热度:667   发布时间:2012-09-06 10:37:01.0
[转]setTimeout 与setInterval 在不同浏览器上运行的差异
setTimeout和setInterval是延时或定时调用某个函数某段代码。基本上是一样的,接下来就只以setTimeout为例。

通常使用形式:

iTimerID = setTimeout(strJsCode, 500)   //strJsCode为一个包含js代码的字符串
iTimerID = setTimeout(objFunction, 500) //objFunction为一个函数对象

看一下下面的代码:

function showArguments() {
	var s = 'length: ' + arguments.length;
	for (var i = 0; i < arguments.length; i++)
		s += ' [' + i + ']: ' + arguments[i];
	alert(s);
}

setTimeout(showArguments, 500, 'parallelism', 'serialization');


结果:
IE: length: 0
Firefox: length: 3 [0]: parallelism [1]: serialization [2]: 0
Chrome: length: 2 [0]: parallelism [1]: serialization

可以看出,结果有很大的不同。

1. IE中的setTimeout

setTimeout Method
    Evaluates an expression after a specified number of milliseconds has elapsed.

Syntax
    iTimerID = window.setTimeout(vCode, iMilliSeconds [, sLanguage])

Parameters
    vCode               Required. Variant that specifies the function pointer or string that indicates
                                    the code to be executed when the specified interval has elapsed.
    iMilliSeconds     Required. Integer that specifies the number of milliseconds.
    sLanguage       Optional. String that specifies one of the following values:
                                  JScript Language is JScript.
                                  VBScript Language is VBScript.
                                  JavaScript Language is JavaScript.



setTimeout接收3个参数,第3个参数表示脚本语言的类型,如果你再传入更多的参数,是无意义的。


2. Mozilla中的setTimeout

window.setTimeout
    Summary
        Executes a code snippet or a function after specified delay.

    Syntax
        var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
        var timeoutID = window.setTimeout(code, delay);


但是有个bug,就是刚才例子中的出现的第三个参数

"Lateness" argument
                Functions invoked by setTimeout are passed an extra "lateness" argument in Mozilla,
                i.e., the lateness of the timeout in milliseconds. (See bug 10637 and bug 394769.)



3. 其它浏览器(Opera, Safari, Chrome)的setTimeout

和Mozilla系列中的基本一样,但是没有Mozilla系列中的多一个参数的BUG.


解决

1. IE中给setTimeout中的调用函数传参数:

// Applicable in non-IE browsers
setTimeout(showArguments, 500, 'parallelism', 'serialization');

// Commonly applicable in all of the browsers
setTimeout(function() {
  showArguments('parallelism', 'serialization');
}, 500);


2. this问题:

setTimeout调用的函数被执行时的上下文是全局,而不再是调用setTimeout方法时的上下文。所以,setTimeout的第一个参数的函数被执行时其this是指向window的,如果需要保留调用setTimeout方法时的this,就需要把当时的this传进去。示例:

function Integral(name) {
    this.name = name;
    var derive = function() { alert(this.name); }
    // Not applicable    
//    setTimeout(derive, 500);
    var THIS = this;
    // Either of the statements below is ok
    setTimeout(derive.apply(THIS), 500);
    setTimeout(derive.call(THIS), 500);
}

new Integral('amount');