定时器

setTimeout()

<body>
<a href="http://www.baidu.com" target="_blank">百度</a>
<button id="btn">跳转</button>
<script>
    //一次性定时器,js属于单线程
    //里面的命令输入回调函数 1000毫秒=1秒
    //不等待,解决数据阻塞
    var timer=setTimeout(function(){
        console.log('走动了');
    },2000);
    console.log('ddd');//这个会先打印

    // clearTimeout(timer);//清楚一次性定时器,只打印ddd
    var oBtn=document.getElementById('btn');
    oBtn.onclick=function(){
        //全局刷新,让整个文档重新解析了一遍,一般不建议使用
        window.location.reload();

    }

</script>
</body>
</html>

setInterval():周期性定时器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #box{
            100px;
            height:100px;
            background-color: red;
        }
    </style>
</head>
<body>
<div id="box"></div>
<script>
    var oDiv=document.getElementById('box');
    var num=0;
    //周期性定时器
     setInterval(function(){
         num++;
         // console.log(num);
         oDiv.style.marginLeft=num+'px'
     },10)  //让div移动

</script>
</body>
</html>

定时器是异步运行的,用定时器的时候,先清定时器,再开定时器

原文地址:https://www.cnblogs.com/mmyy-blog/p/9536753.html