Simple timer implemented by javascript and javascript Timer
I recently wrote many interactive games, such as the limited-time clicks to win prizes, limited-time puzzles, and limited-time Q & amp; A games, all of which are limited-time 'game' (not actually games, at most, it is a little entertaining interaction)
There are four limitations above, right. That's right. Here we record the latest 'timer '...
Well, the timer can be implemented with either setInterval or setTimeout. The Code will not exceed 10 lines!
But you can't write a reusable timer with nothing to do with it.
1. Countdown and timing
2. Reset, pause, stop, and start
// Timer window. timer = (function () {function mod (opt) {// configurable parameters all carry the default value // required parameter this. ele = typeof (opt. ele) = 'string '? Document. getElementById (opt. ele): opt. ele; // element // optional parameter this. startT = opt. startT | 0; // time base this. endT = opt. endT = 'undefined '? 24*60*60: opt. endT; // The default end time is one day. this. setStr = opt. setStr | null; // concatenate strings this. countdown = opt. countdown | false; // countdown this. step = opt. step | 1000; // The parameter this. timeV = this. startT; // current time this. startB = false; // whether timing is enabled this. pauseB = false; // whether to pause this. init ();} mod. prototype = {constructor: 'timer', init: function () {this. ele. innerHTML = this. setStr (this. timeV) ;}, start: function () {if (this. pauseB = t Rue | 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 method:
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 input method setStr is the string processing before the current time calculated by the counter is written to ele.
Whether countdown is a countdown. By default, countdown is used.
You can use timerO. timeV to obtain the current time.
The above is all the content of this article. I hope you will like it.