2015-06-07 48 views
1

我試圖每4秒更改一次背景,但它直接跳到第二個條件並且不再更改。這是爲什麼發生?setInterval不重複

var time = 1; 
var func = function() { 
    'use strict'; 

    if (time === 1) { 
     document.getElementById("top-background").style.backgroundColor = "#000"; 
     time += 1; 
    } 

    if (time === 2) { 
     document.getElementById("top-background").style.backgroundColor = "#aaa"; 
     time += 1; 
    } 

    if (time === 3) { 
     document.getElementById("top-background").style.backgroundColor = "#d5d5d5"; 
     time -= 2; 
    } 

}; 

setInterval(func, 4000); 
+1

如果您在if子句中增加值,它會立即匹配下一個if子句。一個簡單而常見的錯誤。 –

回答

6

嘗試使用else if

var func = function() { 
    'use strict'; 

    if (time === 1) { 
     document.getElementById("top-background").style.backgroundColor = "#000"; 
     time += 1; 
    } 

    else if (time === 2) { 
     document.getElementById("top-background").style.backgroundColor = "#aaa"; 
     time += 1; 
    } 

    else if (time === 3) { 
     document.getElementById("top-background").style.backgroundColor = "#d5d5d5"; 
     time -= 2; 
    } 

}; 
+1

它的工作,謝謝!我會在11分鐘內將它作爲答案進行檢查。 –

2

當時間等於1,您添加到時間。這使得時間等於2.之後,你檢查時間是否等於2,這是!這會使您繼續向上,直到達到時間等於3的點,然後再次將其重置爲1。

您需要一種方法來檢查只有一個條件。您可以使用if和elseif來執行此操作:

if (time == 1) { 
    // Code... 
} else if (time == 2) { 
    // Code... 
} else { 
    // Code... 
    // Because it's not equal to 1 or 2, it must be 3. 
} 

或者,您也可以使用JavaScript的Switch語句。

switch(time) { 
    case 1: 
    // Code... 
     break; 
    case 2: 
    // Code... 
    break; 
    case 3: 
    // Code... 
    break; 
    default: 
    // Something went wrong and it's not 1, 2, or 3 
    }