浅谈js的setInterval事件

setInterval() 方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭。由 setInterval() 返回的 ID 值可用作 clearInterval() 方法的参数。

setinterval()用法

setInterval(code,millisec[,"lang"])

后面就两个参数code是你的js代码,millisec为时间间隔,以毫秒计

<body>

   <div id="content"  style="position:relative; height:1000px; width:1000px; background-color:#666;">

    <div id="one" style="position:absolute;top:0px; left:0px; height:100px; width:100px; background-color:red;"></div>

    </div>

        <script>

          var one=document.getElementById('one')

          var x=0;

          var y=0;

          var xs=10;

          var ys=10;

          function scroll(){

              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

function show(){ trace("每隔一秒我就会显示一次");}

var sh;sh=setInterval(show,1000);

clearInterval(sh);

例2

<form>

<input type="text" id="clock" size="35" />

<script language=javascript>

var int=self.setInterval("clock()",50)

function clock(){var t=new Date()

document.getElementById("clock").value=t

}

</script>

</form>

<div id="clock"></div>

<button onclick="int=window.clearInterval(int)">Stop interval</button>

以上是 浅谈js的setInterval事件 的全部内容, 来源链接: utcz.com/z/315497.html

回到顶部