jQuery計時器
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>無標題文檔</title>
<script type="text/javascript" src="jquery.min.js"></script>
<style>
.btnl,btnr{ width:60px;height:25px;}
</style>
</head>
<body>
<input type="text" class="showTime">
<button class="btnl">開始</button>
<button class="btnr">結束</button>
<script type="text/javascript">
var timeIndex = 0;
$(".btnl").click(function(){ //點擊btnl觸發setTime()函數
setTime();
times = setInterval(setTime, 1000); //每隔1秒執行函數
});
$(".btnr").click(function(){
clearInterval(times); //清除對函數的調用
});
function setTime(){
var hour = parseInt(timeIndex / 3600); // 計算時
var minutes = parseInt((timeIndex % 3600) / 60); // 計算分
var seconds = parseInt(timeIndex % 60); // 計算秒
hour = hour < 10 ? "0" + hour : hour;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
$(".showTime").val(hour + ":" + minutes + ":" + seconds);
timeIndex++;
}
</script></pre>
parseInt() 函數可解析一個字符串,并返回一個整數。
setInterval() 方法會不停地調用函數,直到 clearInterval() 被調用或窗口被關閉。
由 setInterval() 返回的 ID 值可用作 clearInterval() 方法的參數。
來自:
jQuery計時器
