重复调用的定时器
var timer = null;
if (timer) clearInterval(timer);
fun();
timer = setInterval(fun,1000);
function fun(){
}
if (timer) clearInterval(timer);
只调用一次的定时器
setTimeout(function () {
},5000);
倒计时
window.onload = function () {
var oOldDate = new Date("2016/8/8 23:30:30");
var oNewDate = new Date("2016/8/9 00:00:00");
var nChaZhi = oNewDate.getTime()-oOldDate.getTime();
var chaMiao = 1000;
var chaFen = chaMiao*60;
var chaShi = chaFen*60;
var timer = null;
if (timer) clearInterval(timer);
funShowTime();
timer = setInterval(funShowTime,1000);
function funShowTime(){
nChaZhi-=1000;
var miao = parseInt(nChaZhi%chaFen/chaMiao);
var fen = parseInt(nChaZhi%chaShi/chaFen);
var shi = parseInt(nChaZhi/chaShi);
console.log(shi+"时"+fen+"分"+miao+"秒");
if (nChaZhi==0){
if (timer) clearInterval(timer);
}
}
}
短信倒计时

<div id="box" class="box">
<input type="text" />
<button>点击发送短信</button>
</div>
* {
margin: 0;
padding: 0;
}
.box {
margin: 100px 100px;
}
window.onload = function () {
var oBox = document.getElementById("box");
var oInput = oBox.getElementsByTagName("input")[0];
var oButton = oBox.getElementsByTagName("button")[0];
var timer = null;
oButton.onclick = function() {
var nChaZhi = 10;
var that = this;
if (timer) clearInterval(timer);
funSendMessage();
timer = setInterval(funSendMessage,1000);
function funSendMessage(){
if (nChaZhi>=0) {
that.disabled = nChaZhi;
that.innerHTML = "剩余"+nChaZhi+"秒";
if (nChaZhi==0){
that.innerHTML = "重新发送短信";
if (timer) clearInterval(timer);
}
}
nChaZhi--;
}
}
}