Talk about js setInterval events

  • 2020-03-30 04:29:34
  • OfStack

The setInterval() method calls the function until clearInterval() is called or the window is closed. The ID value returned by setInterval() can be used as an argument to the clearInterval() method.
Use the setinterval ()

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

The following two parameters code is your js code, millisec for the time interval, in milliseconds


<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>

Here's a simple example.

Case 1


function show(){ trace(" I'll show it every second ");}
var sh;sh=setInterval(show,1000);
clearInterval(sh);

Case 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>


Related articles: