setTimeout("function",time) 设置一个超时对象
clearTimeout(对象) 清除已设置的setTimeout对象
var time1;
showTime();
function showTime()
{
var today = new Date();
alert("The time is: " + today.toString());
time1 = setTimeout("showTime()", 5000);
}
function cleartime()
{
clearTimeout(time1);
}
showTime()每执行一次似乎会设置一个超时对象
执行cleartime()时,若showTime()执行了多次,会需要cleartime()多次。
这样改一下:
var time1;
showTime();
function showTime()
{
clearTimeout(timer1); // 清除已设置的setTimeout对象
var today = new Date();
alert("The time is: " + today.toString());
time1 = setTimeout("showTime()", 5000);
}
function cleartime()
{
clearTimeout(time1);
}
故障演示(把一下代码放到txt文件里,把你的txt文件改成htm文件格式):
<html>
<head>
<title>setTimeout与clearTimeout</title>
<script language="javascript" type="text/javascript">
var time1;
showTime();
function showTime()
{
//clearTimeout(time1);
time1 = setTimeout("showTime()", 1000);
a=new Date(); //创建a为一个新的时期对象
s=a.getSeconds(); //获取当前秒钟数
if (s%2 == 0)
{
var hrr = document.getElementById("hrr");
hrr.style.color = "red";
}
else
{
var hrr = document.getElementById("hrr");
hrr.style.color = "";
}
}
function cleartime()
{
clearTimeout(time1);
}
</script>
</head>
<body>
<a href="#" οnclick="showTime()">start</a><br />
<a href="#" οnclick="cleartime()"> end</a><br />
<hr id='hrr' width="100%" height="3px" /></body>
</html>
步骤:一、打开htm文件(ie),允许javascript。
二、看见闪烁,点end,闪烁停止,点start又开始闪烁。
三、连续点几次start,点一次end,是否停止闪烁?
四、取消“//clearTimeout(time1); ”的“//”,尝试步骤三,是否停止闪烁?
--------------谁来教我?求指点。-------------------