JS中的定时器

在JS中的定时器分两种:

  1,setTimeout()

  2,setInterval()

setTimeout():

  只在指定时间后执行一次:

function hello(){
    alert('hello');
}
// 使用方法名字执行方法
var t1 = window.setTimeout(hello,1000);
//一般第一个元素写入函数名
var t2 = window.setTimeout("hello()",3000)  // 使用字符串执行方法
window.clearTimeout(t1); // 去掉定时器。

setInterval():

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

<script type="text/javascript">
        window.onload = function(){
            var oapp = document.getElementById('app');
            var movebtn = document.getElementById('move');
            var count = 0;
            var timer = null;
            movebtn.onclick = function(){
                timer = setInterval(function(){
                    count += 3;
                    if(count>=500){
                        clearInterval();
                    }
                    oapp.style.marginLeft = count + 'px';},50);
            }
        }
    </script>
</head>
<body>
    <div id="app" style="100px;height: 100px;border:1px solid red"></div>
    <button id ='move'>移动</button>
</body>

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

原文地址:https://www.cnblogs.com/stfei/p/9112179.html