简体   繁体   English

清除 Javascript 中的超时后,如何取消 setTimeout() 中的事件

[英]How do I cancel the event in a setTimeout() after clearing the timeout in Javascript

So I'm trying to make a live console for a Discord so that I can see errors while I'm away from my computer.所以我正在尝试为 Discord 制作一个实时控制台,以便在我离开计算机时可以看到错误。 I'm trying to make it so that every time the listener will receive data it will clear the previous timeout and make a new one so that the same thing is not sent x amount of times because the listener was called x amount of times.我试图做到这一点,每次侦听器接收数据时,它都会清除先前的超时并创建一个新的超时,这样相同的事情就不会发送x次,因为侦听器被调用x次。 Now I'm at my problem.现在我遇到了我的问题。 I can clear the timeout but not the event inside of it.我可以清除超时但不能清除其中的事件。

child.stdout.on("data", (data) => {
    stdout = stdout + data.toString();

    clearTimeout(timeout);

    timeout = setTimeout(() => {
        message.channel.send([stdout], {
            code: true,
            split: true
        });
    })
});

So this code ends up still sending x amount of times.所以这段代码最终仍然发送了x次。 How would I cancel the event inside to fix this?我将如何取消里面的事件来解决这个问题?

Edit: Dumb mistake by me.编辑:我犯了一个愚蠢的错误。 I accidentally deleted the timeout while cleaning up my code.我在清理代码时不小心删除了超时。 The code bellow solves everything.下面的代码解决了一切。

child.stdout.on("data", (data) => {
    stdout = stdout + data.toString();

    clearTimeout(timeout);

    timeout = setTimeout(() => {
        message.channel.send([stdout], {
            code: true,
            split: true
        });
    }, 3000)
});

Dumb mistake by me.我的愚蠢错误。 I accidentally deleted the timeout while cleaning up my code.我在清理代码时不小心删除了超时。 The code bellow solves everything.下面的代码解决了一切。

child.stdout.on("data", (data) => {
    stdout = stdout + data.toString();

    clearTimeout(timeout);

    timeout = setTimeout(() => {
        message.channel.send([stdout], {
            code: true,
            split: true
        });
    }, 3000)
});

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

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