I'm learning to develop an ExpressJS API and I need to know how to delay the call of a function but to answer the client with a success code even if the process has not ended.
A simple code sample would be:
router.post('/', (req,res) => {
if(req.body.success) {
createRecord(req.body); // I need this function to be called after X minutes
}
return res.status(201).send(`Record will be created in X min from ${now}.`)
});
While searching I found the function setTimeout. However, is not clear to me how does it work.
I hope someone could help me to clarify my doubts. Thanks.
If you don't know setTimeout
then you don't understand the event loop in JS. Here's a talk that you REALLY need to watch!
Meanwhile I'll briefly explain the basics.
You know that when you call a function, it'll exec each line of code in its body in time order, up till it hits a return, throws an error, or reaches the last line.
When one of the line is a call to setTimeout(myDelayedFn, 1000)
, the call to setTimeout itself is executed in time order. It sends a request to the runtime, telling it to SCHEDULE a call to myDelayedFn
AT LEAST 1000ms later.
Not to confuse the term request I used here is NOT network request. You can think of it as a signal.
So setTimeout just sends a request for a scheduled work, but that work is not executed. Execution of myDelayedFn
falls out of time order since it's SCHEDULED. It also means you normal line-by-line execution order is not interrupted (we say it doesn't BLOCK the execution). After sending the request, execution continues to next line in function body.
This means "no", "yes", "yes" to your 3 questions.