Copy codeThe Code is as follows:
SetTimeout (function (obj ){
Alert (obj. );
}, 2000, {a: 1 });
The third parameter is passed, and the third parameter is passed as the callback function's parameter obj. 1 is displayed in a non-IE browser. This solution solves the execution context of the callback function. For example, to call a method of an object, you can pass the object through parameters.
Copy codeThe Code is as follows:
SetTimeout (function (obj ){
Obj. method ();
}, 2000, obj );
Of course, you can also pass multiple parameters to the callback function, as shown below:
Copy codeThe Code is as follows:
SetTimeout (function (a, B ){
Alert ();
Alert (B );
}, 2000, 1, 2 );
This time we passed two parameters 1 and 2 to the callback function, and Firefox/Safari/Chrome/Opera popped up 1 and 2. You can upload more information as long as you want.
Although IE does not support the third parameter, there is a difference between Firefox and Safari/Chrome/Opera.
Copy codeThe Code is as follows:
SetTimeout (function (){
Alert (arguments. length );
}, 2000, 1, 2 );
Two Parameters 1 and 2 are passed to the callback function, and alert returns the length of the real parameter.
Firefox: 3
Safari/Chrome/Opera: 2
It is strange that two parameters are clearly passed, but 3 is displayed in Firefox. If the third parameter is output, it is a number, sometimes a negative number.
Off:
Http://www.w3.org/TR/Window/
Https://developer.mozilla.org/en/DOM/window.setTimeout
Http://msdn.microsoft.com/en-us/library/ms536753%28v=vs.85%29.aspx
// Solve the bug of setTimeout parameter passing in IE
Copy codeThe Code is as follows:
// Solve the bug of setTimeout parameter passing in IE
If (! + [1,]) {
(Function (overrideFun ){
Window. setTimeout = overrideFun (window. setTimeout );
Window. setInterval = overrideFun (window. setInterval );
})(
Function (originalFun ){
Return function (code, delay ){
Var args = []. slice. call (arguments, 2 );
Return originalFun (
Function (){
If (typeof code = 'string '){
Eval (code );
}
Else {
Code. apply (this, args );
}
},
Delay
)
}
}
);
}