アプリケーションのためのタイマーの種類を書きました.

1566 ワード

/**
 *         author:littlehow
 *   2015-04-25
 *  @param time     --            
 *  @param fname    --    
 *  @param loopflag --     -1       0     ( timeout)           
*/
function Timer(time, fname, loop){
	if(this instanceof Timer){
		this.id = -1;
		this.time = time;
		this.fname = fname;
		this.stopFlag = false;
		this.loop = this.count = this.currentCount = 0;
		if(typeof loop=="number"){
			this.loop = this.count = loop;
		}
		this.myFun = function(obj){
			return function(){
				if(--obj.count<=0){
					obj.stop();
				}
				obj.currentCount++;
				obj.fname();
			};
		};
		
		this.newFun = function(obj){
			return function(){
				obj.currentCount++;
				obj.fname();
			};
		};
		
		this.start = function(){
			this.currentCount = 0;
			this.stopFlag = false;
			if(this.loop==-1){
				this.id = window.setInterval(this.newFun(this),this.time);
			}else if(this.loop==0){
				this.id = window.setTimeout(this.fname, this.time);
			}else{
				this.id = window.setInterval(this.myFun(this), this.time);
			}
		};
		this.stop = function(){
			if(this.stopFlag){
				return;
			}else{
				this.stopFlag = true;
			}
			if(this.loop==0){
				window.clearTimeout(this.id);
			}else{
				window.clearInterval(this.id);
			}
		};
		this.setTime = function(time){
			this.time = time;
		};
		this.setLoop = function(loop){
			this.loop = loop;
		};
		this.setFname = function(fname){
			this.fname = fname;
		};
		this.getId = function(){
			return this.id;
		};
	}else{
		return new Timer(time, fname, loopflag);
	}
};