1. 程式人生 > >js定時器的使用

js定時器的使用

這兩種定時器方法都會返回一個id,可以通過這個id來提前終止它們.

一次性定時器,只執行一次 

一次性定時器
    //推遲N毫秒執行一次函式,執行完之後,
    //自動停止,也可以在未執行前手動停止.
    var id;
    function f5(){
        //啟動定時器,若想在未執行定時器
        //前就將它停止,需要使用id
        id = setTimeout(function(){
            console.log("頂頂頂");
        },3000);
    }
    function f6(){
        //若定時器已經執行,則取消無效
        //若定時器還未執行,則可以取消
        clearTimeout(id);
    }

<input type="button" value="按鈕5"
        onclick="f5();"/>
    <input type="button" value="按鈕6"
        onclick="f6();"/>

週期性定時器 

 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
    #clock{
        border:1px solid red;
        width:200px;
        text-align:center;
        line-height:30px;
        font-size:20px;
        height:30px;
    }
</style>
<script>
    var id;
    function start(){
        //若id非空,則定時器已啟動過,
        //那麼就不要再次啟動了
        if(id){
            return;
        }
        id = setInterval(function(){
            //獲取當前客戶端的時間
            var d = new Date();
            //獲取本地格式的時間
            var now = d.toLocaleTimeString();
            //將時間寫入clock
            var p = document.getElementById("clock");
            p.innerHTML = now;
            
        },1000)
    }
    function stop(){ 
        //id非空時定時器處於啟動狀態,
        //此時停止它才有效.
        if(id){
            clearInterval(id);
            //為了可以再次啟動,將id清空
            id=0;
        }
    }
</script>
</head>
<body>
    <input type="button" value="開始"
        onclick="start();"/>
    <input type="button" value="暫停"
        onclick="stop();"/>
    <p id="clock"> 
        
 
    </p>
</body>
</html>