0

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.

  1. 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');
  1. 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)
  1. 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.

Josue
  • 21
  • 2
  • 1
    What makes you think the first approach seems like a hack? – mr5 Dec 20 '19 at 05:01
  • Not too sure, I always was taught that code belongs *inside* of the setTimeout, I am quite fond of the method, just wanted to know if there are any downsides from it – Josue Dec 20 '19 at 05:17
  • If your concern aims for single threaded environment only, I think the first approach is the cleanest among the three. [Look here](https://stackoverflow.com/a/39914235/2304737) for more details in the first approach. – mr5 Dec 20 '19 at 06:12

1 Answers1

0

I don't know if this an answer you want. but this package might be useful. https://www.npmjs.com/package/delay

  • Yeah that is what I am looking for, but it looks like an over complicated version of the first method. I'm really considering choosing that one. – Josue Dec 20 '19 at 05:20
  • if you only want to delay your messages , No another feature you need in the package. I think you can just use the first approaches. it's the cleanest and easiest to use. – Natapon Sripetchpun Dec 20 '19 at 06:31
  • the package only useful when you want to clear out the delay like "hey user please type in you password with in 3 min". if he type in you can use `delay.signal` to cancel the delay and call the function you want. – Natapon Sripetchpun Dec 20 '19 at 06:44