setTimeout()与clearTimeout()

setTimeout(code,millisec)
setTimeout() 只执行 code 一次。如果要多次调用,请使用 setInterval() 或者让 code 自身再次调用 setTimeout()。
实例:
<html>
<head>
<script type="text/javascript">
function timedMsg()
{
var t=setTimeout("alert('5 seconds!')",5000)
}
</script>
</head>

<body>
<form>
<input type="button" value="Display timed alertbox!"
onClick="timedMsg()">
</form>
<p>Click on the button above. An alert box will be
displayed after 5 seconds.</p>
</body>

</html>

clearTimeout() 方法可取消由 setTimeout() 方法设置的 timeout。

语法:

clearTimeout(id_of_settimeout)
实例:
<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()
  {
  clearTimeout(t)
  }
</script>
</head>
<body>

<form>
<input type="button" value="Start count!" onClick="timedCount()">
<input type="text" id="txt">
<input type="button" value="Stop count!" onClick="stopCount()">
</form>

</body>
</html>

 

posted @ 2018-04-13 17:17  迪迪的博客  阅读(8751)  评论(0编辑  收藏  举报