var timer=setInterval('date_2();', 3000); | 每隔3秒循环执行过程函数! |
clearInterval(timer) ; | 可以关闭一个定时器 |
一、基础实例
<script language="JavaScript">
function date_1()
{
alert('打开网页只执行一次过程函数!');
}
function date_2() {
alert('每隔3秒循环执行过程函数!');
}
// settimeout(date_1(), 3000); //打开网页只执行一次过程函数!
setInterval('date_2();', 3000); //每隔3秒循环执行过程函数!
//setTimeout("alert('这是进入网页执行,只执行一次!')", 3000)
//setInterval("alert('这是进入网页执行,每隔3秒执行一次!')", 3000)
</script>
二、轮播图定时器效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>主页</title>
<link rel="stylesheet" href="css/body.css" />
</head>
<style>
.logo {
width: 300px;
height: 300px;
background-color: #999999;
border: 5px rgb(204, 201, 201) solid;
overflow: hidden;
}
.logo img {
width: 100%;
height: 100%;
}
button {
width: 150px;
height: 60px;
font-size: 25px;
margin-right: 20px;
}
</style>
<body>
<div class="logo">
<img src="images/logo.jpg" />
</div>
<br /><br />
<button id="stop">停止定时器</button>
<button id="btn_2">下一张</button>
</body>
<script type="text/javascript">
var img = document.getElementsByTagName("img")[0];
var img_now=0;
var imgs=["tb1.jpg","tb2.jpg","tb3.jpg","tb4.jpg","tb5.jpg"];
var stop = document.getElementById("stop");
stop.onclick = function () {
clearInterval(lunbo);
};
var btn_2 = document.getElementById("btn_2");
btn_2.onclick = function ()
{
img_now=img_now+1;
if(img_now==5){img_now=0};
img.src="images/"+imgs[img_now];
}
/* 每一秒切换一张图片 */
var lunbo=setInterval(btn_2.onclick,1000);
</script>
</html>