一种轻量级的、功能丰富的jQuery插件创建计时器容易管理计时器在您的项目。
tinytimer插件允许您根据需要保存和恢复计时器实例。即使你的电脑关机了,它也能确保你的计时器保持跟踪。
此外,该插件还支持动态计数器更新、可自定义的时间格式以及基本的onTick()和onTargetReachd()事件处理程序。
1.在文档中下载并加载tinytimer插件的压缩版(~2.5kb)。
<script src="/path/to/cdn/jquery.min.js"></script> <script src="/path/to/dist/jquery.tinytimer.min.js"></script>
2.创建一个新的计时器实例。
<div class="jt-counter"> Counter! </div>
const myTimer = $(".jt-counter").timer();
3.自定义计时器的可用选项。
$(".jt-counter").timer({
// initial value
timerCounter: 0,
// target value
timerTarget: 0,
// tick interval in milliseconds
refreshInterval: 1000,
// formatter function
updateHtml: function() {
// using getTimezoneOffset makes this work with all timezones
var d = new Date( "Thu Jan 01 1970 00:00:00" );
var f = new Date( this.counter + d.getTimezoneOffset() * 60000 );
this.html(
( "0" + ( ( f.getDate() - 1 ) * 24 + f.getHours() ) ).substr( -2 ) + ":" +
( "0" + ( f.getMinutes() ) ).substr( -2 ) + ":" +
( "0" + ( f.getSeconds() ) ).substr( -2 )
);
},
});
4.事件处理程序
$(".jt-counter").timer({
onTargetReached: function() {
// do something here
},
onTick: function() {
console.log(
"Counter value: " + this.counter + "\n" +
"Target: " + this.target + "\n" +
"Is Running: " + this.enabled + "\n" +
"Current history: " + JSON.stringify(this.history)
);
}
});
5.管理计时器的可用方法。
// start myTimer.start(); // stop myTimer.stop(); // reset myTimer.zero(); // destroy myTimer.destroy(); // remove myTimer.remove(); // update myTimer.counter = 60*1000;