setTimeout的通常用法是干什么我就不多说了,上次看到一个setTimeout的一个用法:

 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]);
}

虽然这个并不是什么好的用法,这里setTimeout的第三个参数主要得到了除IE外的系列浏览器的支持,具体说明可以参考这篇文章

http://www.cnblogs.com/snandy/archive/2011/05/18/2050315.html

后面的留言也给出了一个扩展IE对象让其支持第三个参数的方法:

(function(w){
//ie传入第三个参数
if(!+[1,]){//除IE外,!+[1,]都是返回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)


如果有第三个参数,某些情况下的调用就可以方便的处理回调函数中当前对象的问题,写起来好看点。

扩展一下Function,增加一个延时调用(参考而已):

   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');

 

下面是一个模拟进度条的例子:

View Code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<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>
</head>
<body>
<div >new Load('loading',600);
load_1.start();
</script>
</body>
</html>




相关文章:

  • 2021-06-07
  • 2022-12-23
  • 2021-08-16
  • 2021-11-08
  • 2022-12-23
  • 2021-12-15
  • 2021-05-29
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-05-28
  • 2022-12-23
  • 2019-12-05
  • 2022-03-08
  • 2021-12-03
  • 2022-12-23
相关资源
相似解决方案