浅谈js的setInterval事件
setInterval()方法会不停地调用函数,直到clearInterval()被调用或窗口被关闭。由setInterval()返回的ID值可用作clearInterval()方法的参数。
setinterval()用法
setInterval(code,millisec[,"lang"])
后面就两个参数code是你的js代码,millisec为时间间隔,以毫秒计
<body> <divid="content" style="position:relative;height:1000px;width:1000px;background-color:#666;"> <divid="one"style="position:absolute;top:0px;left:0px;height:100px;width:100px;background-color:red;"></div> </div> <script> varone=document.getElementById('one') varx=0; vary=0; varxs=10; varys=10; functionscroll(){ x+=xs; y+=ys; if(x>=document.getElementById('content').offsetWidth-one.offsetWidth-20||x<=0) { xs=-1*xs; } if(y>=document.getElementById('content').offsetHeight-one.offsetHeight-20||y<=0) { ys=-1*ys; } one.style.left=x; one.style.top=y; } dt=setInterval(scroll,100); one.onmouseover=function(){ clearInterval(dt); }; one.onmouseout=function(){ dt=setInterval(scroll,100); }; </script> </body>
下面举一个简单的例子。
例1
functionshow(){trace("每隔一秒我就会显示一次");} varsh;sh=setInterval(show,1000); clearInterval(sh);
例2
<form> <inputtype="text"id="clock"size="35"/> <scriptlanguage=javascript> varint=self.setInterval("clock()",50) functionclock(){vart=newDate() document.getElementById("clock").value=t } </script> </form> <divid="clock"></div> <buttononclick="int=window.clearInterval(int)">Stopinterval</button>