1.计时器
(1)setInterval()
在执行时,从载入页面后每隔指定的时间执行代码。
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>定时器</title>
<script type="text/javascript">
var attime;
function clock(){
var time=new Date();
attime= time.getHours()+":"+time.getMinutes()+":"+time.getSeconds() ;
document.getElementById("clock").value = attime;
}
var int=setInterval(clock,100);
</script>
</head>
<body>
<form>
<input type="text" id="clock" size="50" />
</form>
</body>
</html>
(2) clearInterval()
clearInterval() 方法可取消由 setInterval() 设置的交互时间。
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>计时器</title>
<script type="text/javascript">
function clock(){
var time=new Date();
document.getElementById("clock").value = time;
}
var i=setInterval("clock()",100);
function mm(){
i=setInterval("clock()",100);
}
</script>
</head>
<body>
<form>
<input type="text" id="clock" size="50" />
<input type="button" value="Stop" onclick="clearInterval(i)"/>
<input type="button" value="Start" onclick="mm()"/>
</form>
</body>
</html>
(3)setTimeout
setTimeout()计时器,在载入后延迟指定时间后,去执行一次表达式,仅执行一次。
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>计时器</title>
</head>
<script type="text/javascript">
var num=0;
function startCount() {
document.getElementById('count').value=num;
num=num+1;
setTimeout("startCount()",1000);
}
setTimeout("startCount()",1000);
</script>
</head>
<body>
<form>
<input type="text" id="count" />
</form>
</body>
</html>
(4)clearTimeout
setTimeout()和clearTimeout()一起使用,停止计时器。
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>计时器</title>
</head>
<script type="text/javascript">
var num=0;
var i;
function startCount(){
document.getElementById('count').value=num;
num=num+1;
i=setTimeout("startCount()",1000);
}
function stopCount(){
clearTimeout(i);
}
</script>
</head>
<body>
<form>
<input type="text" id="count" />
<input type="button" value="Start" onclick="startCount()" />
<input type="button" value="Stop" onclick="stopCount()" />
</form>
</body>
</html>
例子:
进入页面5s倒计时后自动跳到另一页面
<!DOCTYPE html>
<html>
<head>
<title>浏览器对象</title>
<meta http-equiv="Content-Type" content="text/html; charset=gkb"/>
</head>
<body>
<!--先编写好网页布局-->
操作成功<br/>
<span id="text"></span>秒后回到主页 <a href="" onclick="history()">返回</a>
<script type="text/javascript">
var num=5;
//获取显示秒数的元素,通过定时器来更改秒数。
function setTime(){
document.getElementById("text").innerText=num;
num--;
setTimeout("setTime()",1000) ;
}
setTime();
//通过window的location和history对象来控制网页的跳转。
function windowopen(){
window.location.assign("www.imooc.com");
}
setTimeout("windowopen()",5000);
function history(){
window.history.back();
}
</script>
</body>
</html>