Home  >  Article  >  Web Front-end  >  Only IE does not support the third or more parameters of the setTimeout/setInterval function_javascript tips

Only IE does not support the third or more parameters of the setTimeout/setInterval function_javascript tips

WBOY
WBOYOriginal
2016-05-16 18:06:201648browse
Copy code The code is as follows:

setTimeout(function(obj){
alert(obj.a );
}, 2000, {a:1});

The third parameter is passed, and the third parameter will be passed in as the parameter obj of the callback function. 1 pops up in non-IE browsers. This has the advantage that it solves the execution context of the callback function. For example, if you want to call a method of an object, you can pass the object in through parameters.
Copy code The code is as follows:

setTimeout(function(obj){
obj. method();
}, 2000, obj);

Of course, you can also pass multiple parameters to the callback function, as follows
Copy code The code is as follows:

setTimeout(function(a, b){
alert(a);
alert(b);
}, 2000, 1,2);

This time we passed two parameters 1,2 to the callback function, and 1,2 popped up in Firefox/Safari/Chrome/Opera in turn . You can send more if you want.

Although IE does not support the third parameter, there are still differences between Firefox and Safari/Chrome/Opera
Copy code The code is as follows:

setTimeout(function(){
alert(arguments.length);
}, 2000, 1,2);

Pass two parameters 1 and 2 to the callback function, and then alert the length of the actual parameters
Firefox: 3
Safari/Chrome/Opera: 2
It’s strange, it’s clearly passed There are two parameters, but the one that pops up in Firefox is 3. If you output the third parameter, you will find that it is a number, sometimes negative.
Close:

http://www.w3.org/TR/Window/

https://developer.mozilla.org/en/DOM/window.setTimeout

http://msdn.microsoft.com/en-us/library/ms536753(v=vs.85).aspx
//Solve the bug of setTimeout parameter passing under IE

Copy code The code is as follows:

//Solve the bug of setTimeout parameter passing under 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
)
}
}
);
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn