I have my Nodejs Cloud Function executing some quick tasks upon invocation. I need to delay its termination by 20 seconds. What is the way to do this in the code?
Asked
Active
Viewed 431 times
-2

Doug Stevenson
- 297,357
- 32
- 422
- 441

Ocean Overflow
- 339
- 2
- 14
-
4You shouldn't have to delay a function by a set amount of time. That's an antipattern for pretty much any code that's trying to be efficient. You should instead return a promise that resolves when all the work is actually complete. – Doug Stevenson Mar 28 '22 at 19:45
-
I need to it for testing purposes to simulate cloud functions cascade invocations. – Ocean Overflow Mar 28 '22 at 19:55
-
I suggest that your quest explain in more detail what you're trying to accomplish first, and indicate what you tried that that doesn't work the way you expect. I think you might be trying to find a solution to a problem that you don't fully understand yet. – Doug Stevenson Mar 28 '22 at 20:36
-
Already got my answer. To answer your comment: I have a sequence of cloud functions with some heavy tasks exchanging data and states through the Firestore. For testing purposes I want to simulate their running timeline but without heavy calculation guts. – Ocean Overflow Mar 28 '22 at 21:19
-
Testing really shouldn't involve forcing a wait time. There is undoubtedly a better way to get this job done without simply adding time that produces no work or outcome. There are mocking or stubbing frameworks that can help you factor out expensive calls to other libraries. – Doug Stevenson Mar 28 '22 at 21:34
1 Answers
2
Assuming you absolutely need this and you will not use this in production, this should be pretty straightforward if this is an asynchronous function.
Just define an async function that will return after an arbitrary amount of time:
async function sleepMS(timeMS) {
await new Promise(res => setTimeout(res, timeMS))
}
then after all your code runs and before your function returns, call it with the amount of time you wish
await sleepMS(20 * 1000)

Abraham Labkovsky
- 1,771
- 6
- 12