# "delay" in function

**URL:** https://discourse.nodered.org/t/delay-in-function/65521
**Category:** FAQs
**Created:** [24 July 2022 08:35 UTC](https://discourse.nodered.org/t/delay-in-function/65521 "2022-07-24T08:35:12Z")
**Posts on this page:** 13
**Page:** 1

<div class="post-metadata">

### Author: ![mikabytes](https://avatars.discourse-cdn.com/v4/letter/m/ecc23a/32.png) [@mikabytes](https://discourse.nodered.org/u/mikabytes)
#### Post date: [24 July 2022 08:35 UTC](https://discourse.nodered.org/t/delay-in-function/65521/1 "2022-07-24T08:35:12Z")

</div>

I've seen several requests for a delay feature in the "function" node. The typical answer is that there is no delay method in JavaScript. Although this is true, you can easily build your own like this:

```auto
const delay = ms => new Promise(res => setTimeout(res, ms))

for (i = 0; i < 12; i++) {
   node.send({
       payload: `I've waited ${i*75}ms`,
   })
   await delay(75)
}

```

This enables a more flexible and powerful way of building flows that are dependent on time.

Next example, I turn on 100 spotlights using MQTT, each one being turned on faster than the next, making it feel like it's speeding up.

```auto
for (i = 0; i < 100; i++) {
    node.send({
        payload: true,
        topic: `livingroom/spotlights/${i}/set`
    })
    await delay(500 - i * 5)
}

```

---

<div class="post-metadata">

### Author: ![TotallyInformation](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/totallyinformation/32/31_2.png) [@TotallyInformation](https://discourse.nodered.org/u/TotallyInformation)
#### Post date: [24 July 2022 13:25 UTC](https://discourse.nodered.org/t/delay-in-function/65521/2 "2022-07-24T13:25:20Z")

</div>

Thanks for this. Moving to FAQ's to make it easier for people to find.

---

<div class="post-metadata">

### Author: ![TotallyInformation](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/totallyinformation/32/31_2.png) [@TotallyInformation](https://discourse.nodered.org/u/TotallyInformation)
#### Post date: [24 July 2022 13:57 UTC](https://discourse.nodered.org/t/delay-in-function/65521/3 "2022-07-24T13:57:24Z")

</div>

I should also have said that I don't know that using a promise and await is always a good idea here? I can see why you've done it for the specific case you've used. But in general, using await will block the exit of the function node (I think - not tested) which may cause issues in certain cases.

Generally, I use setTimeout directly but write the timeout reference to a context variable so that it can be cancelled if needed.

---

<div class="post-metadata">

### Author: ![dceejay](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/dceejay/32/38_2.png) [@dceejay](https://discourse.nodered.org/u/dceejay)
#### Post date: [24 July 2022 15:14 UTC](https://discourse.nodered.org/t/delay-in-function/65521/4 "2022-07-24T15:14:24Z")

</div>

if you do use setTimeout (or setInterval) in a function I think we automatically clear them up on close so unless you need to cancel for other reasons no need to save the handle to it.

---

<div class="post-metadata">

### Author: ![davidz](https://avatars.discourse-cdn.com/v4/letter/d/a88e57/32.png) [@davidz](https://discourse.nodered.org/u/davidz)
#### Post date: [24 July 2022 15:27 UTC](https://discourse.nodered.org/t/delay-in-function/65521/5 "2022-07-24T15:27:15Z")

</div>

Yes we use exactly the same approach. It is very useful to simplify flows for repeated operations that needs a slight delay in each iteration.

---

<div class="post-metadata">

### Author: ![mikabytes](https://avatars.discourse-cdn.com/v4/letter/m/ecc23a/32.png) [@mikabytes](https://discourse.nodered.org/u/mikabytes)
#### Post date: [25 July 2022 07:20 UTC](https://discourse.nodered.org/t/delay-in-function/65521/6 "2022-07-25T07:20:36Z")

</div>

I believe it's safe. Timeouts/Intervals should be handled automatically (await/async is just syntactic sugar).

Cancelling execution could be achieved like this (written on phone, untested):

```auto
const delay = ms => new Promise(res => context.set("timer", setTimeout(res, ms)))

for (i = 0; i < 12; i++) {
   node.send({
       payload: `I've waited ${i*75}ms`,
   })
   await delay(75)
}

```

```auto
const cancel = () => clearTimeout(context.get("timer"))

if (someCondition) {
    cancel()
}

```

---

<div class="post-metadata">

### Author: ![TotallyInformation](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/totallyinformation/32/31_2.png) [@TotallyInformation](https://discourse.nodered.org/u/TotallyInformation)
#### Post date: [25 July 2022 09:28 UTC](https://discourse.nodered.org/t/delay-in-function/65521/7 "2022-07-25T09:28:19Z")

</div>

> [@mikabytes](#):
>
> I believe it's safe. Timeouts/Intervals should be handled automatically (await/async is just syntactic sugar).

As mentioned. I'm sure that the code you posted is OK. It is more that I'm not entirely convinced that it would be safe in a general sense since I'm sure that I read that there is something about `await` being blocking. So if you had a more complex timeout function, the function node wouldn't exit until it completed. If you had a rapid input of msgs to that fn node, that might cause a backlog.

Anyway, not tested but thought it worth mentioning for future reference. The promise and await aren't really necessary.

---

<div class="post-metadata">

### Author: ![knolleary](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/knolleary/32/3_2.png) [@knolleary](https://discourse.nodered.org/u/knolleary)
#### Post date: [25 July 2022 09:59 UTC](https://discourse.nodered.org/t/delay-in-function/65521/8 "2022-07-25T09:59:27Z")

</div>

> [@TotallyInformation](#):
>
> `await` being blocking

`await` does not block the event loop. It is syntactic sugar for Promises that avoids writing code with lots of callbacks/then-blocks.

---

<div class="post-metadata">

### Author: ![TotallyInformation](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/totallyinformation/32/31_2.png) [@TotallyInformation](https://discourse.nodered.org/u/TotallyInformation)
#### Post date: [25 July 2022 19:54 UTC](https://discourse.nodered.org/t/delay-in-function/65521/9 "2022-07-25T19:54:19Z")

</div>

I don't think I explained it well. I know that it doesn't block the event loop.

I think this explains the possible pitfalls better than I can:  
[Understanding async-await in JavaScript | by Gokul N K | Better Programming](https://betterprogramming.pub/understanding-async-await-in-javascript-1d81bb079b2c).

---

<div class="post-metadata">

### Author: ![mikabytes](https://avatars.discourse-cdn.com/v4/letter/m/ecc23a/32.png) [@mikabytes](https://discourse.nodered.org/u/mikabytes)
#### Post date: [28 July 2022 14:55 UTC](https://discourse.nodered.org/t/delay-in-function/65521/10 "2022-07-28T14:55:08Z")

</div>

Hmm. I went through that article but still struggle to see the potential problem(s).

Nothing is blocking in the sense that the JavaScript engine will stop. I can imagine Node-RED could potentially have an issue though, is that what you meant?

Could you provide an example that demonstrates the potential issue?

If there is a specific problem related to Node-RED, then I would like to file it as a bug. Perhaps I'll even spend some time fixing it.

---

<div class="post-metadata">

### Author: ![TotallyInformation](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/totallyinformation/32/31_2.png) [@TotallyInformation](https://discourse.nodered.org/u/TotallyInformation)
#### Post date: [28 July 2022 15:46 UTC](https://discourse.nodered.org/t/delay-in-function/65521/11 "2022-07-28T15:46:08Z")

</div>

> [@mikabytes](#):
>
> I can imagine Node-RED could potentially have an issue though, is that what you meant?

Yes. You could potentially get a backlog of requests that haven't completed.

As I said, the example given is fine and won't be a problem, this was more about people making assumptions about await as a general solution in _all_ cases. It seems to me that there are edge cases that need care (as with much of JavaScript!)

> [@mikabytes](#):
>
> If there is a specific problem related to Node-RED, then I would like to file it as a bug

No "bug", it is a "feature" of how promises with await works. Nothing wrong with node-red.

---

<div class="post-metadata">

### Author: ![mikabytes](https://avatars.discourse-cdn.com/v4/letter/m/ecc23a/32.png) [@mikabytes](https://discourse.nodered.org/u/mikabytes)
#### Post date: [28 July 2022 18:13 UTC](https://discourse.nodered.org/t/delay-in-function/65521/12 "2022-07-28T18:13:54Z")

</div>

Alright. Thanks for clearing that up, I understand your point now.

The same danger is true for callbacks that never return or very long timeouts. There has to be something wrong with the code itself. await/async or promises is just a detail.

I don't recommend always using this await-delay approach. I prefer the delay node where appropriate because my flows become more visually understandable. This trick is for the case where more flexibility is required.

---

<div class="post-metadata">

### Author: ![system](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/1X/d073cd938eafa2e558d7c2cd59003b3ef4963033.png) [@system](https://discourse.nodered.org/u/system)
#### Post date: [26 September 2022 18:14 UTC](https://discourse.nodered.org/t/delay-in-function/65521/13 "2022-09-26T18:14:50Z")

</div>

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.
