clearInterval只終止定時器不終止函數

如下代碼

this.timer=setInterval(function(){
            if(index==listArray.length){
                listArray[listArray.length-1].style.backgroundColor='#fff';         
                clearInterval(dftBtn.timer);
            }
            render(listArray,index++);
        },1000);

此時瀏覽器報錯,

Uncaught TypeError: Cannot read property ‘style’ of undefined

說明會導致棧溢出,因爲會訪問到listArray[listArray.length],那麼導致這個問題出現的原因不難分析:確實clearInterval終止了this.timer這個定時器,但是並沒有終止函數,所以此次函數還是要執行完,即會接着執行一次render(listArray,index++);函數,若要解決這個問題也簡單,緊跟着clearInterval之後return一下就好了。
如下:

this.timer=setInterval(function(){
            if(index==listArray.length){
                listArray[listArray.length-1].style.backgroundColor='#fff';         
                clearInterval(dftBtn.timer);
                ***return;***
            }
            render(listArray,index++);
        },1000);
發佈了44 篇原創文章 · 獲贊 117 · 訪問量 28萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章