简体   繁体   English

等待递归 function 完成 javascript

[英]Wait for recursive function to complete javascript

I'm quite rusty on my javascript and I'm using the code from this answer in a text game to animate text.我对我的 javascript 很生疏,我在文本游戏中使用这个答案中的代码来动画文本。

Show text letter by letter 逐个字母显示文本

var showText = function (target, message, index, interval) {   
    if (index < message.length) {
      $(target).append(message[index++]);
      setTimeout(function () { showText(target, message, index, interval); }, interval);
    }
}

I'd like to wait until its finished to reveal a button but no matter how I edit it, nothing seems to wait, it just moves on right away.我想等到它完成来显示一个按钮,但无论我如何编辑它,似乎什么都没有等待,它只是立即移动。 Is there any solution or better way to show the text?是否有任何解决方案或更好的方法来显示文本?

I added an if statement inside of the setTimeout so that when the last letter shows, the button will show at the same time.我在 setTimeout 中添加了一个 if 语句,这样当最后一个字母显示时,按钮将同时显示。 If I added it as an else if of the existing if statement, it waited the interval time after the last letter was shown to show the button.如果我将它添加为现有 if 语句的 else if,它会在显示最后一个字母后等待间隔时间以显示按钮。

 var showText = function(target, message, index, interval) { if (index < message.length) { $(target).append(message[index++]); setTimeout(function() { showText(target, message, index, interval); if (index == message.length - 1) { $("#btn").show() } }, interval); } } showText($("#box"), "TEST", 0, 1000)
 #btn { display: none }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="box"></div> <button id="btn">Show</button>

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

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