本文我们用 中的setTimeout()和 clearTimeout()方法实现倒计时效果
由于有了setTimeout()和 clearTimeout(),在JavaScritp中使用计时事件成了一件很容易的事,所以按照自己的简单想法,写了一个倒计时效果,时间到后显示一个相应的图片。
xhtml:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"">
<html xmlns="">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="gb2312" />
<title>倒计时演示</title>
<meta name="Author" content="Cuoxin(建站学), longchina@Cuoxin.com" />
<style type="text/css">
#t2{display:none;}
</style>
</head>
<body>
<div id="test">
<input id="t1" type="button" onclick="detonate();" value="倒计时开始" />
<input id="t2" type="button" onclick="demolite();" value="停止倒计时" />
</div>
</body>
</html>
javascript:
<script type="text/">
var x = document.getElementById("test");
var x2 = document.getElementById("t1");
var x3 = document.getElementById("t2");
var c = 10;
var timeId1 = 0;
function detonate(){
x3.style.display = "inline";
x2.value = "倒计时";
x2.value += c--;
if(c >= 0){
timeId1 = window.setTimeout(detonate,1000);
}else{
x2.style.display = "none";
x3.style.display = "none";
bomb = document.createElement("div");
bomb.innerHTML = "<img src='http://www.jzxue.com/wangzhankaifa/javascript-ajax/201103/1.jpg' alt='bomb' />";
document.body.appendChild(bomb);
}
}
function demolite(){
window.clearTimeout(timeId1);
x3.style.display = "none";
alert("时间到。请注意。");
x2.value = "继续";
}
</script>