js 定时器

一.定时器

在js中的定时器分两种:1、setTimeout() 2、setInterval()

1.setTimeOut()

只在指定时间后执行一次

定时器 异步运行  
function hello(){  
alert("hello");  
}  
//使用方法名字执行方法  
var t1 = window.setTimeout(hello,1000);  
var t2 = window.setTimeout("hello()",3000);//使用字符串执行方法  
window.clearTimeout(t1);//去掉定时器

2.setInterval()

在指定时间为周期循环执行

/实时刷新  时间单位为毫秒  
setInterval('refreshQuery()',8000);   
/* 刷新查询 */  
function refreshQuery(){  
  console.log('每8秒调一次') 
}

两种方法根据不同的场景和业务需求择而取之,

对于这两个方法,需要注意的是如果要求在每隔一个固定的时间间隔后就精确地执行某动作,那么最好使用setInterval,而如果不想由于连续调用产生互相干扰的问题,尤其是每次函数的调用需要繁重的计算以及很长的处理时间,那么最好使用setTimeout

实例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        #box{
            width: 100px;
            height: 100px;
            background-color: red;
        }
    </style>
</head>
<body>
    <button id="start">开启定时器</button>
    <button id="clear">清除定时器</button>
    <div id="box"></div>
    <!-- 定时器
        
        (1)一次性定时器
             可以做异步
        (2)循环周期定时器
            可以做动画

            js跟python一样 都有垃圾回收机制

            but 定时器对象 垃圾回收收不回


            开一次性定时器:
            var timer = setTimeout(fn,1000);
            开循环定时器
            setInterval(fn,1000);
            
            clearTimeout()
            clearInterval()
     -->

     <script>
         /*
         var timer = null;
         document.getElementById('start').onclick = function() {
             
             // 未来 数据交互的时候 如果数据阻塞了,可以考虑 加一个一次性定时器来处理
             timer  = setTimeout(function(){
                 console.log(1111);
             },3000);
             console.log(2222);

         }
         document.getElementById('clear').onclick = function() {
             clearTimeout(timer);
         }
         */
         var count = 0;
         var timer = null;
         document.getElementById('start').onclick = function() {

             var oDiv = document.getElementById('box');
             clearInterval(timer);
             
             timer = setInterval(function() {
                 count+=10;

                 oDiv.style.marginLeft = count + 'px';
                 
             }, 50)

         }
     </script>
</body>
</html>
原文地址:https://www.cnblogs.com/zwq-/p/9714090.html