通过使用 JavaScript,我们有能力做到在一个设定的时间间隔之后来执行代码,而不是在函数被调用后立即执行。我们称之为计时事件。
点击按钮之后,警告框会在5秒后显示
<html>
<head>
<script type="text/javascript">
function timedMsg()
{
var t=setTimeout("alert('5 秒!')",5000)
}
</script>
</head>
<body>
<form>
<input type="button" value="显示定时的警告框" onClick = "timedMsg()">
</form>
<p>请点击上面的按钮。警告框会在 5 秒后显示。</p>
</body>
</html>
10S倒计时
<html>
<head>
<script type="text/javascript">
function timedText()
{
var t1=setTimeout("document.getElementById('txt').value='9 秒'",1000)
var t2=setTimeout("document.getElementById('txt').value='8 秒'",2000)
var t3=setTimeout("document.getElementById('txt').value='7 秒'",3000)
var t4=setTimeout("document.getElementById('txt').value='6 秒'",4000)
var t5=setTimeout("document.getElementById('txt').value='5 秒'",5000)
var t6=setTimeout("document.getElementById('txt').value='4 秒'",6000)
var t7=setTimeout("document.getElementById('txt').value='3 秒'",7000)
var t8=setTimeout("document.getElementById('txt').value='2 秒'",8000)
var t9=setTimeout("document.getElementById('txt').value='1 秒'",9000)
var t10=setTimeout("document.getElementById('txt').value='0 秒',alert('炸死你')",10000)
}
</script>
</head>
<body>
<form>
<input type="button" value="显示计时的文本" onClick="timedText()">
<input type="text" id="txt" value="10 秒">
</form>
<p>点击上面的按钮。输入框会显示出已经逝去的时间(2、4、6 秒)。</p>
</body>
</html>
带起始和停止的
<html>
<head>
<script type="text/javascript">
var c=0
var t
function timedCount()
{
document.getElementById('txt').value=c
c=c+1
t=setTimeout("timedCount()",1000)
}
function stopCount()
{
c=0;
setTimeout("document.getElementById('txt').value=0",0);
clearTimeout(t);
}
</script>
</head>
<body>
<form>
<input type="button" value="开始计时!" onClick="timedCount()">
<input type="text" id="txt">
<input type="button" value="停止计时!" onClick="stopCount()">
</form>
<p>请点击上面的“开始计时”按钮来启动计时器。输入框会一直进行计时,从 0 开始。点击“停止计时”按钮可以终止计时,并将计数重置为 0。</p>
</body>
</html>
显示时钟
<html>
<head>
<script type="text/javascript">
function startTime()
{
var today=new Date()
var h=today.getHours()
var m=today.getMinutes()
var s=today.getSeconds()
// add a zero in front of numbers<10
m=checkTime(m)
s=checkTime(s)
document.getElementById('txt').innerHTML=h+":"+m+":"+s
t=setTimeout('startTime()',500)
}
function checkTime(i)
{
if (i<10)
{i="0" + i}
return i
}
</script>
</head>
<body οnlοad="startTime()">
<div id="txt"></div>
</body>
</html>
JavaScript 计时事件
通过使用 JavaScript,我们有能力作到在一个设定的时间间隔之后来执行代码,而不是在函数被调用后立即执行。我们称之为计时事件。
在 JavaScritp 中使用计时事件是很容易的,两个关键方法是:
-
setTimeout()
- 未来的某时执行代码 clearTimeout()
- 取消setTimeout()
setTimeout()
语法
var t=setTimeout("javascript语句",毫秒)
setTimeout() 方法会返回某个值。在上面的语句中,值被储存在名为 t 的变量中。假如你希望取消这个 setTimeout(),你可以使用这个变量名来指定它。
setTimeout() 的第一个参数是含有 JavaScript 语句的字符串。这个语句可能诸如 "alert('5 seconds!')",或者对函数的调用,诸如 alertMsg()"。
第二个参数指示从当前起多少毫秒后执行第一个参数。
提示:1000 毫秒等于一秒。
clearTimeout()
语法
clearTimeout(setTimeout_variable)