JavaScript的计时器

来源:互联网 发布:中国骨科手术量数据 编辑:程序博客网 时间:2024/06/11 14:22
setInterval(函数,毫秒); 每隔毫秒数执行一次函数:
定时器是一个带有时间概念一个东西,对比for循环是瞬间完成没有时间概念,都是重复执行代码
少了定时器的页面将会减少了很多有意思的效果

例子:

var i =0;

function fn1(){document.title = i;i++}

setInterval(fn1,1000);

也是除了函数()和元素.事件=函数,这两种调用函数方法外第三种调用函数的方法setInterval的最小间隔:一般写20及以上,太快可能反应不过来

clearInterval()把要停止的定时器放进去,清除掉
一般var timer = setInterval(),然后清除这个变量就可以了

例子:

var timer = null; var i =0;

function fn1(){document.title = i;i++;
if(i===10){clearInterval(timer);}}
timer = setInterval(fn1,1000);

注意上面的代码执行顺序

练习1:设置两个按钮,一个'换背景',一个'停',并给body设置一个背景(如1,2,3,4放数组里),点击'换背景'时,每隔3秒变成下一张,点击'停'则不再切换

bug:每次点击都会开始一个定时器,速度会越来越快,修改--每次点击的时候关掉之前的计时器再开新的计时器(如果计时器由用户控制则一定记得)

<body><input type="button" value="走"/><input type="button" value="停"/><script>var arr = ["url(img/1.png)","url(img/2.png)","url(img/3.png)","url(img/4.png)"];var aBtn = document.getElementsByTagName("input");var i=0;var timer = null;aBtn[0].onclick = function(){clearInterval(timer);timer = setInterval(function(){i>2?i=0:i++;document.body.style.backgroundImage = arr[i];},1000)}aBtn[1].onclick = function(){clearInterval(timer);}</script></body>


练习2:用开关的方法把这个功能集中在一个按钮上面

<body><input type="button" value="走走停停"/><script>var arr = ["url(img/1.png)","url(img/2.png)","url(img/3.png)","url(img/4.png)"];var aBtn = document.getElementsByTagName("input");var i=0;var bOnOff = true;var timer = null;aBtn[0].onclick = function(){if(bOnOff){timer = setInterval(function(){i>2?i=0:i++;document.body.style.backgroundImage = arr[i];},1000)}else{clearInterval(timer);}bOnOff = !bOnOff;}</script></body>
setTimeout(函数,毫秒);延时毫秒数执行一次函数:
相对应的清除clearTimeout(timer);

练习1:5秒后弹出一个广告(随便一个网站截屏做背景)

练习2:在练习1的基础上在广告右上角加个关闭按钮,让它展示4秒消失或者点击关闭按钮消失

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><style type="text/css">body{margin:0; background-image:url(img/1.png);}#div1{width:600px; height:400px; text-align:center; line-height:400px; background-color:#fff; font-size:100px; position:fixed; top:50%; left:50%; margin-top:-200px; margin-left:-300px; display:none;}span{width:25px; height:25px; background-color:#ccc; text-align: center; line-height:25px; color:red; position:absolute; top:5px; right:5px; font-size:14px; cursor:pointer;}</style></head><body><div id="div1">广告弹窗<span>X</span></div><script>var oDiv = document.getElementById("div1");var oSpan = oDiv.getElementsByTagName("span")[0];setTimeout(function(){oDiv.style.display = "block";setTimeout(dis,4000);},3000)oSpan.onclick = dis;function dis(){oDiv.style.display = "none";}</script></body></html>
练习3:把之前的作业(4个按钮和4个图片的效果),做成每隔3秒自动切换一张
练习4:在练习3的基础上做一个鼠标移入时让自动滚动停止的效果

<body><div id="div1"></div><img src="img/1.png" width="391" height="479"/><script>var arr = ["img/1.png","img/2.png","img/3.png","img/4.png"];var oDiv = document.getElementById("div1");var oImg = document.getElementsByTagName("img")[0];var str = "";for(var i=0;i<arr.length;i++){str += "<input type='button' value='"+(i+1)+"'/>";}oDiv.innerHTML = str;var aBtn = oDiv.getElementsByTagName("input");for(var i=0;i<aBtn.length;i++){aBtn[i].index = i;aBtn[i].onclick = function(){oImg.src = arr[this.index];iNow = this.index;}}var iNow = 0;var timer = setInterval(fn,1500);oImg.onmouseover = function(){clearInterval(timer);}oImg.onmouseout = function(){timer = setInterval(fn,1500);}function fn(){iNow>2?iNow=0:iNow++;oImg.src = arr[iNow];}</script></body>
练习5:QQ显示详细内容,鼠标移入展示,移出消失,要求--鼠标离开过一小段时间再消失(1.5秒),移动到展示内容上时,不消失,从展示上离开后(1.5秒)再消失

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><style type="text/css">body{margin:0;}#div1{left:0;top:0; width:150px; height:150px; background-color:#0F9; position:absolute;}#div2{left:170px;top:0; width:150px; height:250px; background-color:#936; position:absolute; display:none;}</style></head><body><div id="div1"></div><div id="div2"></div><script>var oDiv1 = document.getElementById("div1");var oDiv2 = document.getElementById("div2");var timer = null;function none(){timer = setTimeout(function(){oDiv2.style.display = "none";},1500);}function block(){clearTimeout(timer);oDiv2.style.display = "block";}oDiv1.onmouseover = oDiv2.onmouseover= block;oDiv1.onmouseout = oDiv2.onmouseout = none;</script></body></html>

练习1:四个方向移动

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><style type="text/css">#div1{width:100px; height:100px; background-color:red; position:absolute; top:50px; left:0;}</style></head><body><input type="button" value="向前" id="btn1"/><input type="button" value="向后" id="btn2"/><input type="button" value="向上" id="btn3"/><input type="button" value="向下" id="btn4"/><div id="div1"></div><script src="myJS.js"></script><script>$("btn1").onclick = function(){doMove($("div1"),850,4,"left");}$("btn2").onclick = function(){doMove($("div1"),0,4,"left");}$("btn3").onclick = function(){doMove($("div1"),50,4,"top");}$("btn4").onclick = function(){doMove($("div1"),500,4,"top");}//alert(getStyle(oDiv,"left"));function doMove(obj,end,speed,how,endFn){var oldAttr = parseInt(getStyle(obj,how));speed = end>oldAttr ? speed : -speed;clearInterval(obj.timer);obj.timer = setInterval(function(){var nowAttr = parseInt(getStyle(obj,how))+speed;if(nowAttr>=end&&speed>0||speed<0&&nowAttr<=end){obj.style[how] = end+"px";clearInterval(obj.timer);//if(endFn){endFn();}endFn && endFn();}else{obj.style[how] =nowAttr+"px";}},30)}</script></body></html>
利用doMove来做练习:
在页面上布局平铺20个100X100红色的方块,点击我们的浏览器的窗口时让每个方块每隔0.2秒以每0.1秒30像素的速度掉下来一个,直到所有的方块掉到500的位置

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><style type="text/css">body{margin:0;}ul{padding:0; margin:0;}li{list-style:none; position:absolute; width:50px; height:50px; background-color:red; font-size:40px; color:#fff; line-height:50px; text-align:center; top:0;}</style></head><body><ul id="ul1"></ul><script src="myJS.js"></script><script>var str = "";for(var i=0;i<20;i++){str += "<li>"+(i+1)+"</li>";}$("ul1").innerHTML = str;var aLi = $("ul1").getElementsByTagName("li");for(var i=0;i<aLi.length;i++){aLi[i].style.left = 51*i+"px";}var timer = null;document.onclick = function(){doMove(aLi[0],"top",5,400);var i = 1;timer = setInterval(function(){doMove(aLi[i],"top",5,400);i>=aLi.length-1 ? clearInterval(timer) : i++;},200)}function doMove ( obj, attr, dir, target, endFn ) {        dir = parseInt(getStyle( obj, attr )) < target ? dir : -dir;        clearInterval( obj.timer );        obj.timer = setInterval(function () {                var speed = parseInt(getStyle( obj, attr )) + dir;            // 步长                if ( speed > target && dir > 0 ||  speed < target && dir < 0  ) {            speed = target;        }                obj.style[attr] = speed + 'px';                if ( speed == target ) {            clearInterval( obj.timer );                        /*            if ( endFn ) {                endFn();            }*/            endFn && endFn();                    }            }, 30);}</script></body></html>

0 0
原创粉丝点击