【问题标题】:How to make my code wait for a function before executing the rest? [duplicate]如何让我的代码在执行其余函数之前等待一个函数? [复制]
【发布时间】:2019-11-09 22:16:23
【问题描述】:

我正在为一个不和谐的机器人制作一些东西,但我无法弄清楚这部分......

Discord 一个聊天应用程序,您可以在其中创建服务器和频道供人们交谈,还有机器人,这就是我正在制作的。

基本思想是我写了一个命令,机器人拒绝每个人在聊天中交谈的权限,倒计时开始,当倒计时达到 0 时,机器人允许再次交谈,是的,这是 JoJo 参考。我已经准备好所有的允许和拒绝,只需要这个倒计时工作。

我的问题是我不能让我的代码自行等待。

//some other code

    console.log("Toki uo tomare!")

    var x = 0;
    function  go() {
        console.log(x)
        if (x++ < 5) {
            setTimeout(go, 500);
        }
    }
    go();

    console.log("Toki wa ugokidasu...")

//some other code

我期待看到

Toki uo tomare! 0 1 2 3 4 5 Toki wa ugokidasu...

但是我看到了这个

Toki uo tomare! 0 Toki wa ugokidasu... 1 2 3 4 5

【问题讨论】:

  • 只需将else { ... } 添加到您的go() 函数中,并将最后的console.log 行放在那里。这样当函数调用自身并看到x == 5 时,它将转到else 块并记录该消息。
  • 其他链接的答案,或上面@Andrew 的评论,将为您提供如何正确执行此操作的线索。我将尝试解释这里发生了什么:代码正在按顺序运行。首先是第一行。然后是一个函数定义,它本身什么都不做。然后调用该函数,并运行一次(它也将自己排队等待稍后再次运行)。然后最后一行运行。 500 微秒后,fxn 再次运行,正如它被告知的那样。
  • @GamBar 乐于助人:)

标签: javascript node.js function discord.js


【解决方案1】:

const TalkingDuration=5000;
let canTalk=true;

window.botInterval=setTimeout(function(){
  canTalk=false;
}, TalkingDuration);

setInterval(function(){
  if(canTalk) console.log("Toki uo tomare!");
}, 100);

//So the clients can talk for 5s and then the bot will stop the chat you can use a loop to redo the task each 5s just by adding another setInterval ... Hope you like it

【讨论】:

  • 你的代码只是垃圾邮件Toki uo tomare!,而我需要它来进行各种倒计时,因此我让它记录 X
猜你喜欢
  • 1970-01-01
  • 2021-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多