计时器函数 setInterval()
setInterval() //计时器函数
setInterval(要执行的函数,执行间隔(以毫秒为单位,1000毫秒就是一秒)
setInterval(function(){
console.log(111)
},1000)
定时器函数 setTimeout()
setTimeout();类似于定时炸弹,规定多久以后执行一次内部的函数
用法:与setInterval()相同
setTimeout(“函数”,执行时间);
setInterval(“函数”,10);每隔十秒执行一次;
setTimeout(“函数”,10);十秒以后执行函数,并且只执行一次;
函数自己调用自己的过程,叫做:递归调用;
所以,要记住,递归调用一定要有跳出的条件;
清除计时器 clearInterval()
声明一个变量,把计时器存起来,然后,用清除语句:
var a=setInterval (function(){},1);
clearInterval(a); //清除计时器
setInterval(function(){},1000);//计时器
function fun(){
console.log(“a”)
}
setInterval(fun,1000)
setInterval(‘fun()’,1000)
小案例(倒计时跳转)
<p id="p">5秒后跳转到百度</p>
<script>
var p = document.getElementById("p");
var i = 5;
setTimeout(fun,1000);
function fun(){
i--;
p.innerHTML = i + "秒后跳转到百度";
if(i<=0){
window.location.href='http://www.baidu.com';
}else{
setTimeout(fun,1000)
}
}
</script>
小案例(无缝滚动轮播图)
<style>
*{
margin: 0;
padding: 0;
}
#div{
width: 800px;
height: 300px;
position: relative;
margin: 50px auto;
border: 5px solid silver;
overflow: hidden;
}
ul{
list-style: none;
position: absolute;
width: 2400px;
}
li{
width: 400px;
height: 300px;
line-height: 300px;
text-align: center;
font-size: 40px;
float: left;
}
.a1{
background-color: pink;
}
.a2{
background-color: aqua;
}
.a3{
background-color: blueviolet;
}
.a4{
background-color: yellow;
}
</style>
<div id="div">
<ul id="ul">
<li class="a1">1</li>
<li class="a2">2</li>
<li class="a3">3</li>
<li class="a4">4</li>
<li class="a1">1</li>
<li class="a2">2</li>
</ul>
</div>
<script>
var ul = document.getElementById("ul");
var i = 0;
var t = setInterval(fn,1);
function fn(){
i--;
ul.style.left = i+"px";
if(i<=-1600){
i=0;
}
}
ul.onmouseover = function (){
clearInterval(t);
};
ul.onmouseout = function(){
t = setInterval(fn,1);
}
</script>
小案例(图片无缝滚动轮播图)
<style>
*{
margin: 0;padding: 0;
}
.box{
width: 100%;
height: 470px;
position: relative;
overflow: hidden;
}
ul{
list-style: none;
position: absolute;
}
li{
width: 13440px;
}
img{
height: 470px; float: left;
}
</style>
<div class="box">
<ul id="ul">
<li>![](images/banner_1.jpg)</li>
<li>![](images/banner_2.jpg)</li>
<li>![](images/banner_3.jpg)</li>
<li>![](images/banner_4.jpg)</li>
<li>![](images/banner_5.jpg)</li>
<li>![](images/banner_6.jpg)</li>
<li>![](images/banner_1.jpg)</li>
</ul>
</div>
<script>
var ul = document.getElementById("ul");
var time = null;
var n = 0; // 图片索引
var left = 0; // 向右动的距离
setTimeout(fun,3000);
function fun(){
n--;
if(n<-6){
n = -1;
left = 0; // 重置
ul.style.left = "0px"; // 重置
}
time = setInterval(function(){
left--;
ul.style.left = left + "px";
if(left <= n*1920){
clearInterval(time);
setTimeout(fun,3000);
}
},1);
}
</script>