码迷,mamicode.com
首页 > 其他好文 > 详细

定时器

时间:2018-10-04 23:55:56      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:cti   win   refresh   val   null   res   interval   time   alert   

定时器

在JS中定时器分为两种:

  1. setTimeout( )
  2. setInterval( )

1 . setTimeout( )

只在指定时间后执行一次(一次性定时器) -- 异步运行,不会形成阻塞

//异步运行
function say(){
alert("hello word");
}

//使用方法名字执行方法
var t1 = window.setTimeout(say , 1000) //1000的单位是毫秒

//使用字符串执行方法
var t1 = window.setTimeout("say()",1000)

//清除定时器
window.clearTimeout(t1)

2  . setInterval( )

-----循环定时器

//实时刷新 
setInterval("refreshQuery()",8000)

function refreshQuery(){
console.log("999")
}

下面是几种案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</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>
    <script>
        // var time=null;
        // <!--开启一次性定时器-->
        //
        // document.getElementById("start").onclick=function () {
        //    time=setTimeout(function () {console.log(111)
        //
        //    },1000)
        //
        // }
        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"

           },10)
        };
        //清除定时器
        document.getElementById("clear").onclick=function () {
            clearInterval(timer)
        }

        </script>

</body>
</html>

 

定时器

标签:cti   win   refresh   val   null   res   interval   time   alert   

原文地址:https://www.cnblogs.com/lxx7/p/9743709.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!