I'm building a chatbot in Node.JS and would like an easy way to insert a delay of a few seconds in between messages.
I have come up with 3 different approaches that all work, but none of them feel right, and I am looking for insight on what would be the best method to achieve the delay, and what would be the best one to choose and build upon.
- Pause with async delay() function. It works well, but it seems like a weird approach that is more of a hack than an intended feature
const delay = async time => {
await new Promise(r => setTimeout(() => r(), time))
}
console.log('Message 1');
await delay(1000)
console.log('Message 2');
- Nested setTimeout() functions. This one makes a mess of the code after a few delays.
setTimeout(() => {
console.log('Message 1');
setTimeout(() => {
console.log('Message 2');
// etc...
}, 1000)
}, 1000)
- Multiple setTimeouts with additive timeouts. Calculating the timeout can become a chore, especially when something is inserted or removed.
setTimeout(() => void console.log('Message 1'), 1000)
setTimeout(() => void console.log('Message 2'), 1000 + 1000)
I'm leaning towards this last one, and then using an incrementing variable to represent the total time. The first one feels the cleanest and the most simple to implement.