在浏览网页的时候,我们可以看到很多使用定时器实现的动画,例如:轮播动画,实时时钟 ······等。
定时器简单来说就是,根据你想要实现的样式给元素加上延时的效果。
在JavaScript中,对于定时器的实现,有以下两组方法。
setTimeout()和clearTimeout().
setlnterval()和 clearlnterval().
1.setTimeout() 和 clearTimeout()
在JavaScript中,我们可以使用setTimeout()方法来“一次性”的调用函数,并且可以使用clearTimeout()来取消执行setTimeout().
(1) 定义和用法 :setTimeout() 方法用于在指定的毫秒数后调用函数或计算表达式。
语法 :setTimeout(code,millisec)
说明 :code可以是一段代码,可以是一个函数,也可以是一个函数名。
millisec是时间,单位为毫秒,表示要过时间“?秒”后执行code里的代码。
例 :setTimeout()
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</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>
<script type="text/javascript">
function timedMsg()
{
var t=setTimeo