Salted fish front end-js timer

Salted fish front end-js timer


The functions called regularly by setInterval () and clearInterval () can be called periodically according to the given time (in milliseconds)

// 创建一个定时器,每隔1秒调用一次
var timerId = setInterval(function () {
  var date = new Date();
  console.log(date.toLocaleTimeString());
}, 1000);

// 取消定时器的执行
clearInterval(timerId);

setTimeout()和clearTimeout()

Execute the specified function after the specified number of milliseconds arrives, only once

// 创建一个定时器,1000毫秒后执行,返回定时器的标示
var timerId = setTimeout(function () {
  console.log('Hello Xianyu');
}, 1000);

// 取消定时器的执行
clearTimeout(timerId);

Case: Click on the picture to dance (comic, I did n’t put the picture, please put the picture yourself)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>title</title>
  <style>
    #box{
      position:absolute;
    }
    #box img{
      display: inline-block;
      width: 200px;
      height: 200px;
      border:2px solid #666;
    }
	
  </style>
</head>
<body>
<input type="button" value="go" id="btn1">
<input type="button" value="stop" id="btn2">
<div id="box">
  <img src="" alt="">
  <img src="" alt="">
</div>
<script>
  var xy$=function(id){
    return document.getElementById(id)
  }
  var timeI = "";
  xy$("btn1").onclick=function(){
   //var timeI = setTimeout(function(){
   	var timeI = setInterval(function(){
    //X和Y的坐标为1~200的随机数
      var x = parseInt(Math.random()*200+1);
      var y = parseInt(Math.random()*200+1);
      xy$("box").style.left=x+"px";
      xy$("box").style.top=y+"px";
    },400)
    xy$("btn2").onclick=function(){
  	//clearTimeout(timeI)
  	clearInterval(timeI)
 	 }
  }

</script>
</body>
</html>
Published 166 original articles · 22 praises · 10,000+ views

Guess you like

Origin blog.csdn.net/weixin_45020839/article/details/105399114