如下代碼
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);