Welcome 微信登录

首页 / 脚本样式 / JavaScript / 基于JQuery.timer插件实现一个计时器

先去官网下载jQuery Timers插件 ,然后引用到html中。这里是1.2 version
复制代码 代码如下:
<script src="../Javascripts/Plugins/jquery.timers-1.2.js" type="text/javascript"></script>

然后是HTML,我们可以放一个hidden 的server control存值用,当然这个随你了。
复制代码 代码如下:
<asp:HiddenField ID="hicurrenttime" runat="server" />
<h1>
jQuery Timers Test</h1>
<input type="button" id="btnmaster" value="StartTimer" />
<h2>
Demos</h2>
<div class="demos">
<span id="durationtimerspan"></span>
<br />
<input id="txtresult" type="text" />
</div>

加上JS:
[/code]
$(document).ready(function() {
var countnum = <%=hicurrenttime.Value %>;
$("#btnmaster").toggle(
function() {
$(this).val("StopTimer");
$("#durationtimerspan").everyTime(1000, "testtimer", function(i) {
countnum = countnum + 1;
$(this).html("Duration: " + countnum);
$("#<%=hicurrenttime.ClientID %>").val(countnum);
});
},
function() {
$(this).val("StartTimer");
$("#durationtimerspan").stopTime("testtimer");
$("#txtresult").val(countnum);
});
});
[html]
上面的代码关键的地方是我们用toggle函数,去实现点击Button开关计时器。这个插件有三个方法:
everyTime(interval : Integer | String, [label = interval : String], fn : Function, [times = 0 : Integer])
每次都执行
oneTime(interval : Integer | String, [label = interval : String], fn : Function)
执行一次
stopTime([label : Integer | String], [fn : Function])
停止
最后我们效果如下图: 
 
类似的用法:
复制代码 代码如下:
//每1秒执行函式test()
function test(){
//do something...
}
$("body").everyTime("1s",test);
//每1秒执行
$("body").everyTime("1s",function(){
//do something...
});
//每1秒执行,并命名计时器名称为A
$("body").everyTime("1s","A",function(){
//do something...
});
//每20秒执行,最多5次,并命名计时器名称为B
$("body").everyTime("2das","B",function(){
//do something...
},5);
//每20秒执行,无限次,并命名计时器名称为C
//若时间间隔抵到,但函式程序仍未完成则需等待执行函式完成后再继续计时
$("body").everyTime("2das","C",function(){
//执行一个会超过20秒以上的程式
},0,true);
/***********************************************************
* oneTime(时间间隔, [计时器名称], 呼叫的函式)
***********************************************************/
//倒数10秒后执行
$("body").oneTime("1das",function(){
//do something...
});
//倒数100秒后执行,并命名计时器名称为D
$("body").oneTime("1hs","D",function(){
//do something...
});
/************************************************************
* stopTime ([计时器名称], [函式名称])
************************************************************/
//停止所有的在$("body")上计时器
$("body").stopTime ();
//停止$("body")上名称为A的计时器
$("body").stopTime ("A");
//停止$("body")上所有呼叫test()的计时器
$("body").stopTime (test);

希望这篇POST对您有帮助。Author: Petter Liu