setInterval不重复

Tha*_*des 1 javascript intervals web

我试图每4秒更改一次背景,但是它会直接跳到第二个条件并且不再改变.为什么会这样?

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);
Run Code Online (Sandbox Code Playgroud)

kem*_*ica 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;
    }

};
Run Code Online (Sandbox Code Playgroud)