Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

102
Visualizações
Discord.js wait between sending several files

I'm new to javascript, I made a code that would dump several files on a channel. However, I want that for each file sent, the bot waits about 5-10 seconds and then sends the next file, and so on. With the code I made, the bot waits 5 seconds, but then posts all the files one after another, instead of waiting 5 seconds between each file sent. I hope someone can help, here's the code:

const fs = require('node:fs');

module.exports = {
    name: 'dump',
    description: "dumps files from a folder",
    execute(message, args, command){
        if (command.startsWith("dump")){
            const Dump = fs.readdirSync('./dump/');
            for(const file of Dump){
            const File = String("./dump/" + file);
            setTimeout(function(){ 
                message.channel.send({
                    files: [File]
                    });
            }, 5000);
            }
        }
    }
}

Figured it out, posted correction on answer.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Made it to work with a simple async function. Probably needs improvement because I just recently started coding, although it works.

Working result:

const fs = require('node:fs');

module.exports = {
    name: 'dump',
    description: "dumps files from a folder",
    execute(message, args, command){
        if (command.startsWith("dump")){
            async function dumpFiles() {
                const Dump = fs.readdirSync('./dump/');
                let wait = async (ms) => await new Promise(r => setTimeout(r,ms));
                for(const file of Dump){
                const File = String("./dump/" + file);
                message.channel.send({files: [File]});
                await wait(5000)
                }
            }
            dumpFiles()
        }
    }
}
about 4 years ago · Juan Pablo Isaza Relatório

0

due to the nature of Javascript the code is asynchronous, so in order to wait 5 seconds between each sending, you have to force the code to wait until a send is done.

For example:

const array = ['A', 'B', 'C', 'D', 'E'];

for(const value of array){
   const time = Math.floor(Math.random() * 5000);
   setTimeout(function(){ 
        console.log(`${value} took: ${time}ms`);
     }, time); 
}

If you run that piece of script, you will see that the values are not printed out in order, which means that the time used in the setTimeout is not making the things wait.

So a fix could be to make all the code synchronous, but that will include extra work. There is already a function build-in Javascript to do things with intervals.

You can try out the function setInterval()

https://www.w3schools.com/jsref/met_win_setinterval.asp

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda