简体   繁体   English

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

[英]Using setInterval in function with internal call (js)?

I have such code here. 我这里有这样的代码。 I want to display result with time interval in a few seconds. 我想以几秒钟的时间间隔显示结果。 But it doesn't work. 但这是行不通的。

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");

Can you explain what do I wrong and why doesn't the setInterval doesn't work? 您能解释我做错了什么吗,为什么setInterval不起作用吗?

You seem to be looking for 您似乎在寻找

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);
}

And since you are recursively calling the function again, you probably wanted to use setTimeout instead of setInterval . 并且由于您要再次递归调用该函数,因此您可能想使用setTimeout而不是setInterval

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM