The common usage of setTimeout is as follows:
var arr = [1,9,2,8,3,7,4,6,4,5];
for(var i = 0, len = arr.length; i < len; i++){
setTimeout(function(x){
console.log(x);
},arr[i],arr[i]);
}
Although this is not a good usage, the third parameter of setTimeout is mainly supported by a series of browsers except ie. For details, refer to this article.
Http://www.cnblogs.com/snandy/archive/2011/05/18/2050315.html
The following message also provides a method to extend the IE Object to support the third parameter:
(Function (w ){
// Pass the third parameter to IE
If (! + [1,]) {// except IE ,! + [1,] both return false
(Function (overridefn ){
W. setTimeout = overridefn (W. setTimeout );
W. setinterval = overridefn (W. setinterval );
}) (Function (originalfn ){
Return function (Code, delay ){
VaR ARGs = array. Prototype. Slice. Call (arguments, 2 );
Return originalfn (function (){
If (typeof code = 'string '){
Eval (CODE );
} Else {
Code. Apply (this, argS );
}
}, Delay );
}
})
}
}) (Window)
If there is a third parameter, in some cases the call can easily handle the problem of the current object in the callback function.
Extend the function to add a delayed call (reference only ):
Function.prototype.delay = function(){
var args = Array.prototype.slice.call(arguments,0);
setTimeout(function(fn){
fn.apply('',args.slice(1));
},args[0],this);
}
var fn = function(x){
alert(x)
};
fn.delay(1000,'xesam');
The following is an example of simulating a progress bar:
View code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>loading</title>
<style type="text/css">
#loading{ height: 20px; margin: 0 auto; border: 1px solid #d4d4d4;}
</style>
<body>
<div id="loading"></div>
<script type="text/javascript" src="/project/javascript/common_js/Xe.js"></script>
<script type="text/javascript">
function Load(id,width){
this.ele = document.getElementById(id);
this.indicator = document.createElement('div');
this.width = (width > 0 && width) || 300;
this.init();
}
Load.prototype = {
constructor:Load,
init:function(){
this.ele.style.width = this.width + 'px';
this.ele.appendChild(this.indicator);
var iStyle = this.indicator.style;
iStyle.width = 0;
iStyle.height = '100%';
iStyle.background = '#ff5500';
},
start:function(){
//this.init();
this.loading();
},
loading:function(){
this.timer = setTimeout(function(obj){
var t = obj.indicator.data || 0;
if(t < obj.width){
obj.indicator.style.width = t + 1 +'px';
obj.indicator.data = t + 1;
obj.loading();
}else{
clearInterval(obj.timer);
}
},10,this);
},
stop:function(){
clearTimeout(this.timer);
}
}
var load_1 = new Load('loading',600);
load_1.start();
</script>
</body>