【问题标题】:JavaScript Recursive Delayed Method call [duplicate]JavaScript递归延迟方法调用[重复]
【发布时间】:2016-04-10 04:03:06
【问题描述】:

我想编写一个简单的函数,它使用模式中的新文本每秒更新一个段落元素<p></p>,但是我不确定如何延迟方法调用这是我尝试过的解决方案,但它没有似乎不起作用。如果您删除 setTimeout 方法并将其替换为简单的递归调用,则该函数会按预期打印出模式,但不会延迟打印出它,这正是我想要的。

function printPattern(eventSource, width, height, counter){
    if(height == 1 && counter >= width) {
        return;
    }
    else{
        if(counter >= width){
            eventSource.innerHTML += "<br>";
            //printPattern(eventSource,width,height-1,0);
            setTimeout(printPattern(eventSource,width,height-1,0), 1000)
        }
        else{
            if((counter%2 == 0) ^ (height%2 == 1)){
                eventSource.innerHTML += "O";
            }
            else{
                eventSource.innerHTML += "X";
            }
            //printPattern(eventSource,width,height,counter+1);
            setTimeout(printPattern(eventSource,width,height,counter+1), 1000)
        }
    }
}

function displayPattern(source){
    printPattern(source, 4, 4, 0);
}

【问题讨论】:

    标签: javascript recursion settimeout


    【解决方案1】:

    您将调用printPattern 的结果传递给setTimeout,而不是传递函数本身。你想要:

    setTimeout(function() {
      printPattern(eventSource, width, height, counter+1);
    }, 1000);
    

    【讨论】:

    • 它们正在作为参数传递给printPattern,在给setTimeout的匿名函数中调用。
    • @torazaburo 由于用户希望 1 秒更新一次,他不应该使用 setInterval 来代替吗?
    • @SarathChandra 好吧,这有利也有弊。在这种情况下,他接下来要执行什么取决于情况,所以我认为使用setTimeout没有问题。
    猜你喜欢
    • 2019-06-10
    • 2019-03-15
    • 1970-01-01
    • 2012-12-04
    • 1970-01-01
    • 1970-01-01
    • 2014-05-06
    • 1970-01-01
    • 2015-09-19
    相关资源
    最近更新 更多