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.
CodePudding user response:
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()
}
}
}
CodePudding user response:
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()