在内部调用(js)的函数中使用setInterval?

时间:2018-09-20 18:31:19

标签: javascript html css function ecmascript-6

我在这里有这样的代码。我想以几秒钟的时间间隔显示结果。但这不起作用。

const moveCranes = setInterval(function(plate, slot_a, slot_b, slot_c) {
    if (plate > 0) {
        moveCranes(plate - 1, slot_a, slot_c, slot_b);
        port_a.innerHTML = "Move plate " + plate + " from " + slot_a + " to " + slot_c + "<br />";
    moveCranes(plate - 1,slot_b, slot_a, slot_c);
    }
}, 2000);
moveCranes(input.value,"slot_a","slot_b","slot_c");

您能解释我该怎么办吗,为什么setInterval不能正常工作?

1 个答案:

答案 0 :(得分:3)

您似乎正在寻找

function moveCranes(plate, slot_a, slot_b, slot_c) { /*
^^^^^^^^ */
    setInterval(function() {
//              ^^^^^^^^^^ this inner function takes no parameters
        if (plate > 0) {
            moveCranes(plate - 1, slot_a, slot_c, slot_b);
            port_a.innerHTML = "Move plate " + plate + " from " + slot_a + " to " + slot_c + "<br />";
            moveCranes(plate - 1, slot_b, slot_a, slot_c);
        }
    }, 2000);
}

并且由于您要再次递归调用该函数,因此您可能想使用setTimeout而不是setInterval