1

Is there any way to make a bot wait for some time (for example 5 seconds) before continuing the code? I need something like:

client.on('messageCreate', message => { 
message.channel.send('1st message')
wait(5000)
message.channel.send('2nd message')
wait(5000) 
message.channel.send('3rd message')
})

I tried using setInterval, like many people suggest, but that doesn't seem to be a solution for me. Also I can't use await setTimeout(time) because of SyntaxError: await is only valid in async functions and the top level bodies of modules and TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received 5000

MegaMix_Craft
  • 2,199
  • 3
  • 10
  • 36
  • 2
    Does this answer your question? [What is the JavaScript version of sleep()?](https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep) – Sven Eberth Oct 14 '21 at 23:49
  • 1
    setInterval would be involved in any answer in some fashion, if you share your usage maybe we can figure out the issue. – Dan Oswalt Oct 14 '21 at 23:58
  • 1
    @SvenEberth If I understood answer you suggested correctly, it's not working for me, even tho I have up-to-date node.js version! (`TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received 5000`) – MegaMix_Craft Oct 14 '21 at 23:59
  • 1
    @DanOswalt basically I need to send few messages with some short delay between them – MegaMix_Craft Oct 15 '21 at 00:00
  • 3
    function doThing() { console.log('hi') } setInterval( doThing, 5000); this doesn't work? – Dan Oswalt Oct 15 '21 at 00:01
  • 1
    @DanOswalt as I said, I need to send few messages (and yes, more than 2), and I don't want to use a lot of `setInterval`s because it looks messy in code, and for some reason I have to wait longer than time I set in code – MegaMix_Craft Oct 15 '21 at 00:04
  • 1
    setTimeout or setInterval is going to either be in your code or abstracted out somewhere else. sounds like you want something like in the top comment if the goal is to use setTimeout in a synchronous-looking manner with async/await. – Dan Oswalt Oct 15 '21 at 00:10
  • 1
    You need to share some more details. We don't know how you send the messages. In your question you asked how to wait between these two `console.log`s. You can use the `setTimeout` function for that, there are a lot of examples and [docs](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) for this... Maybe you can use a loop or a callback to handle multiple delays for your messages? – Sven Eberth Oct 15 '21 at 00:13

1 Answers1

2

You can promisify setTimeout with Node's Util library. Then make the messageCreate callback asynchronous.

const wait = require('util').promisify(setTimeout);

client.on('messageCreate', async message => { 
   message.channel.send('1st message')
   await wait(5000)
   
   message.channel.send('2nd message')
   await wait(5000) 
   
   message.channel.send('3rd message')
})
Elitezen
  • 6,551
  • 6
  • 15
  • 29