Recently wrote a lot of micro-client interactive games, such as the next Snowflake Limited Click to win prizes, limited to the puzzle, limited to answer, and so on, are limited to the "game" (in fact, not a game, at most, is a little entertaining small interaction just)
There are 4 time limits, right, yes, this is the most recently written ' Timer ' ...
Well, the timer on a setinterval or settimeout can be achieved, the code will not exceed 10 lines!
But not to hold the mentality of nothing to look for, to write a reusable timer
1. Can count down the clock
2. Reset, pause, stop, start function
Timer Window.timer = (function () {function mod (opt) {//Configurable parameters all with default//Required Parameters This.ele = typeof (Opt.ele) = = ' str ing ' document.getElementById (opt.ele): opt.ele;//elements//Optional Parameters This.startt = opt.startt| | 0;//Time Base This.endt = opt.endt== ' undefined '? 24*60*60:opt.endt;//end time defaults to one day This.setstr = opt.setstr| | null;//string concatenation This.countdown = opt.countdown| | false;//Countdown this.step = opt.step| |
1000; Non-configurable parameter This.timev = this.startt;//Current Time THIS.STARTB = false;//whether to start timing THIS.PAUSEB = false;//whether to suspend This.ini
T (); } Mod.prototype = {constructor: ' Timer ', init:function () {This.ele.innerHTML = This.setstr (THIS.TIMEV)
; }, Start:function () {if (this.pauseb==true| |
THIS.STARTB = = true) {This.pauseb = false;
Return
} if (This.countdown==false&&this.endt<=this.cardinalnum) {return false;
}else if (This.countdown==true&&this.endt>=this.startt) {return false; } THIS.STARTB = true;
var v = this.startt, This_ = this, anim = null; Anim = setinterval (function () {if (this_.startb==false| |
V==this_.endt) {clearinterval (anim); return false} if (This_.pauseb==true) return;
This_.timev = This_.countdown?--v:++v;
This_.ele.innerHTML = This_.setstr (THIS_.TIMEV);
},THIS_.STEP);
}, Reset:function () {THIS.STARTB = false;
This.timev = This.startt;
This.ele.innerHTML = This.setstr (THIS.TIMEV);
}, Pause:function () {if (THIS.STARTB = = true) This.pauseb = true;
}, Stop:function () {THIS.STARTB = false;
} return mod;
})();
Call Mode:
var timero_1 = new Timer ({
ele: ' BOX1 ',
startt:0,
endt:15,
setstr:function (num) {return
num+ ' s ' ;
}
});
var timero_2 = new Timer ({
ele: ' BOX2 ',
startt:30,
endt:0,
countdown:true,
step:500,
setstr:function (num) {return
num+ ' s ';
}
});
The method passed here Setstr is the string processing before the current time that the counter calculates is written to Ele
Countdown whether the countdown defaults to the CIS timing
You can get the current time by Timero.timev
The above mentioned is the entire content of this article, I hope you can enjoy.