JavaScript定時器的簡單運用(暫停,繼續)


1、定時器種類

js定時器有兩個方法:
1、setInterval() :周期性地執行該方法
2、setTimeout() :只執行一次該方法

2、使用方法

兩個方法的使用方式相同,以setInterval()舉例:
setInterval里面有兩個參數:setInterval(1、函數或代碼串, 2、時間間隔)

   setInterval(alert("hello world!"),2000) //每間隔兩秒彈窗一次

3、清除定時器方法

setInterval()使用clearInterval()方法清除,setTimeout()使用clearTimeout()清除
    let timer = setInterval(alert("hello world!"),2000)
    clearInterval(timer) //清除timer定時器

4、定時器的簡單運用(暫停、繼續功能)

適用於輪播圖的暫停、繼續功能

 <button id="btn">鼠標指我</button>
    <script>
        let btn = document.querySelector("#btn")
        let timer = setInterval(function(){
            alert('123')
            },2000)
        //鼠標移入暫停
        btn.addEventListener('mouseover',function(){
            clearInterval(timer)
        })
        //鼠標移出繼續
        btn.addEventListener('mouseout',function(){
            timer = setInterval(function(){
                alert('123')
            },3000)  
        })
    </script>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM