了解知识点
setInterval() 每隔一段时间执行某些代码
clearInterval() 方法停止 setInterval() 方法执行的函数代码
*在生产环境中clearInterval()很少使用。
setTimeout一定时间后执行某些代码
关于定时器时间的规定
据说html5中规定时间不低于10毫秒(就是说浏览器的timer可能会被操作系统影响,)
最小延时 >=4ms(mcn说的)
如果低于10ms,执行顺序就不好说了。比如
(这个问题可能暂时对于我来说没有太大的研究意义,我查阅了相关API 和一些文档,可能涉及到一些浏览器或者操作系统相关原理,总之以目前我的水平,暂时无法理解,所以暂时不再深究)
var timer1=setTimeout(function(){
console.log(timer1);
},3);
var timer2=setTimeout(function(){
console.log(timer2);
},2);
var timer3=setTimeout(function(){
console.log(timer3);
},1);
console.log("start");
执行结果:
如果都改成小于1的毫秒数
两种情况的执行顺序并不相同。
制作下拉广告的步骤
1.让div的高度从0变成250(setInterval)
2.到达指定的高度后需要停止3s(setTimeout)
3.让div的高度从250变化到100(setInterval)
4.运动完成以后要清除定时器
<!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>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
#ad{
background: url(../微信图片_20210413172959.jpg);
}
</style>
<script>
window.onload=function(){
var ad=document.getElementById("ad");
var t1;
var h=parseInt(getComputedStyle(ad).height);
t1=setInterval(function(){
h++;
ad.style.height=h+'px';
// 高度到250时停止运动,接着要停止3s
if(h==250){
clearInterval(t1);
// 停止3s
t2=setTimeout(function(){
t1=setInterval(function(){
// clearTimeout(t2);
h--;
ad.style.height=h+'px';
//让div回到100的位置就停止
if(h=100){
clearInterval(t1);
}
},16);
},3000);
}
},16);
}
</script>
</head>
<body>
<div id="ad"></div>
</body>
</html>