最近写了一个倒计时的控件,共享出来方便使用
用法:var stopwatch = new Stopwatch(“倒计时间/秒”,”倒计时完成时的回调函数”,”每个计时事件回调”,”计时步长/秒”)
stopwatch.start();//开始/继续计时
stopwatch.pause();//暂时计时
stopwatch.restart();//重新开始计时
stopwatch.stop();//停止计时
(function(global, factory) {
// 兼容requirejs和普通引入模式
if (typeof module === "object" && typeof module.exports === "object") {
module.exports = global.document ? factory(global, true) : function(w) {
if (!w.document) {
throw new Error("requires a window with a document");
}
return factory(w);
};
} else {
factory(global);
}
}(typeof window !== "undefined" ? window : this, function(window, noGlobal) {
// 构造方法
var Stopwatch = function(countDownTime, stopedRecall,tickRecall,steparg) {
this.iniTime = parseInt(countDownTime);
if(typeof stopedRecall == "function"){
this.recall = stopedRecall;
}else{
console.error("回调方法必须为function");
return null;
}
if(tickRecall){
if(typeof tickRecall == "function"){
this.tick = tickRecall;
}else{
console.error("回调方法必须为function");
return null;
}
}
this.curtime = countDownTime;
this.status = "stop";
this.step = 1;
if(steparg && steparg > 0){
this.step = steparg;
}
};
if (typeof noGlobal === typeof undefined) {
if (typeof window.Stopwatch === typeof undefined) {
window.Stopwatch = Stopwatch;
} else {
Stopwatch = window.Stopwatch;
}
}
// 对象方法
Stopwatch.prototype.start = function() {
this.status = "counting";
this.curtime = this.iniTime;
this.countDown();
};
Stopwatch.prototype.stop = function() {
this.curtime = this.iniTime;
this.status = "stop";
};
Stopwatch.prototype.pause = function() {
this.status = "pause";
};
Stopwatch.prototype.restart = function() {
this.status = "counting";
this.curtime = this.iniTime;
this.countDown();
};
Stopwatch.prototype.countDown = function() {
if (this.status == "counting") {
if (this.curtime <= 0) {
this.recall();
this.status = "stop";
} else {
this.curtime = this.curtime-this.step;
var $this = this;
this.tick();
window.setTimeout(function() {
$this.countDown();
}, 1000);
}
}
};
Stopwatch.prototype.tick = function(){
if(console&&console.log){
console.log("tick:"+this.curtime);
}
};
Stopwatch.prototype.recall = function(){
if(console&&console.log){
console.log("stoped");
}
};
return Stopwatch;
}));
下载:https://github.com/wamdy/JsUtils/blob/master/src/Stopwatch.js
打赏
微信扫一扫,打赏作者吧~
Like this:
Like Loading...
相关