2016-07-27 41 views
0

我想不通爲什麼我的遞歸超時函數只能通過這些圖像只經過一次。即使我已經在「else」語句中重置了變量「n」,它仍然保持結束。這樣做的目標是改變圖像的z分數以將其交換出去。用圖像交換器遞歸

var n = 0; 
window.onload = imageFade; 

function imageFade(){ 
    for(x=0; x<10; x++){ 
     document.getElementById("image" + x).style.zIndex = 0; 
    } 
    timeout(); 
} 

function timeout() { 
    setTimeout(function(){ 
     if(0 <= n <= 9){ 
      document.getElementById("image" + n).style.zIndex = 1; 
      n++; 
      timeout(); 
     }else{ 
      n=0; 
      timeout(); 
     } 
    }, 1000); 
} 
+1

'如果(0 <= N <= 9){'使用n < 11? – Rayon

+0

這是實現它的唯一方法,因爲'for循環'會立即自動遍歷所有圖像,並且不存在每次迭代計時的「定時循環」。這就是爲什麼我要訴諸於「for循環」和「如果其他」聲明的這種奇怪的混合。 – Mangofett

+0

你*可以*做一個定時循環。 –

回答

1

可以在if條件

var n = 0; 
 
var t = 0; 
 
var timer = null; 
 
timeout(); 
 

 
function timeout() { 
 
    timer = setTimeout(function() { 
 
    if (n < 11) { 
 
     console.log(n); 
 
     ++n; 
 
     timeout(); 
 
    } else { 
 
     n = 0; 
 
     // call `clearTimeout(timer)` following five iterations of `0-10` 
 
     if (++t === 5) { 
 
     clearTimeout(timer); 
 
     return; 
 
     }; 
 
     timeout(); 
 
    } 
 
    }, n === 11 ? 0 :1000); 
 
}

+0

這在父範圍中有很多狀態,因爲'timeout'不指望任何參數。我不會推薦。 – ftor