// 下面是两个私有的单例模式成员 this.Loop = function(){ this.stopLoop = function(){ /* 单次执行的list对象 */ var x = 1; var sum; function Plus(a, b) setTimeout( function(){ sum = Plus(x, y, z); }, 3000);
// 无限循环执行的List对象
var Infinite_loop = new (function(){
this.loop_stop = true;
this.loop_action = new Array();
this.loop_actionID = 0;
var opp = this;
this.setLoopFn = function(fn){
if(typeof(fn)!="function"){
throw new Error("window.loop.setloop's argment is not a function!"); return;
}
for(var i=0;i
throw new Error(fn+" has been registered !");
return;
}
}
this.loop_action.push(fn);
this.startLoop();
};
this.deleteLoopFn = function(fn){
for(var i=0;i
this.loop_action.splice(i,1);
}
}
};
var run = function(){
if(opp.loop_action.length > 0){
(opp.loop_action[opp.loop_actionID])();
opp.loop_actionID++;
if(opp.loop_actionID>=opp.loop_action.length)opp.loop_actionID=0;
setTimeout(opp.Loop,20);
return;
}
opp.loop_stop = true;
};
run();
}
this.loop_stop = true;
}
this.startLoop = function(){
if(! this.loop_stop)return;
this.loop_stop = false;
this.Loop();
}
})();
var one_loop = new (function(){
this.loopOne_stop = true;
this.loopOne_action = new Array();
var opp = this;
this.setLoopOneFn = function(fn){
if(typeof(fn)!="function"){
throw new Error("window.loop.setloopOne's argment is not a function!"); return;
}
this.loopOne_action.push(fn);
this.startLoopOne();
}
this.LoopOne = function(){
function run(){
if(opp.loopOne_action.length>0 && !opp.loopOne_stop){
(opp.loopOne_action.shift())();
setTimeout(opp.LoopOne,20);
return;
}
opp.loopOne_stop = true;
}
run();
}
this.stopLoopOne = function(){
this.loopOne_stop = true;
}
this.startLoopOne = function(){
if(! this.loopOne_stop)return;
this.loopOne_stop = false;
this.LoopOne();
}
})();
})();
下面是实例:loop.html
script>
script>
var y = 2;
var z = 3;
{
var z = 0;
var i = 0;
for (i = 0; i < arguments.length; i++)
{
z += arguments[i];
}
setTimeout( function() {alert(z);}, 6000); //可以带变量参数的setTimeout调用形式
return z;
}
/*除了可以带变量参数还可以获取返回值的setTimeout调用形式*/
其实大家可以再深入思考一下,
例如模拟一个简单工厂类的东西。
var