SetTimeout and SetInterval are two very magical ways of window objects that enable you to call a function or a piece of code periodically or in a delay.
(Novice may think that settimeout and setinterval are JavaScript functions, which is wrong.) Beginners can easily confuse JavaScript object functions with Dom object methods. )
First a piece of code, you can guess what the results will be in various browsers?
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")
What I'm going to explore here is not when to use it, but about the differences between the two methods in each browser.
Originally I did not think these two methods will have what oolong, a chance to let me know, now tidy up and write to share with you.
Because settimeout and setinterval parameters and usage is the same, but the function is different, so, for the sake of convenience, I only take settimeout as an example to illustrate and examples.
The most frequently used form of settimeout is probably the following 2 types:
iTimerID = setTimeout(strJsCode, 50) //strJsCode为一个 包含js代码的字符串
iTimerID = setTimeout(objFunction, 50) //objFunction 为一个函数对象
The first invocation is to pass the string containing the JS code, the advantage of this way is concise, but the disadvantage is inefficient operation, and not conducive to parsing, there are potential risks, more importantly, dealing with more complex content is difficult, this point and eval is consistent with the drawbacks.
Therefore, we believe that it is generally appropriate to use the second method of invocation as well. (In the following example, I use the 2nd invocation method)
Now let's find out the results of the first piece of code under various browsers:
IE (6,7,8) is: arguments.length:0;
Opera (6,7,8) is: arguments.length:2; [0]:javascript; [1]:aaa;
Firefox (3.0) is: Arguments.length:3; [0]:javascript; [1]:aaa; [2]:-15;
There is such a big difference, it is really "you sing your song, I hum my tune"!
Firefox (3.0), the final figure is not specific, sometimes 0, sometimes a negative number, the problem is later.