setTimeout in servless app

I need to add a sleep to freshdesk in a serverless app (to ensure an updates is made before I make a subsequent)

function sleep(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}   

This function is run with:

await sleep(200)

When this function I get following error:

ReferenceError: setTimeout is not defined at Promise (server.js:195:5) 
at new Promise () at sleep (server.js:194:10) 
at validateNewFDContact (server.js:144:28) 
at Object.onContactCreateHandler (server.js:136:5)

Is 'setTimeout()" supported or what can I use in its place?

Hi @stevemc,
Good day!
The serverless component of the app is executed in sandbox mode where some methods, such as setTimeout and setInterval, cannot be used.

kindly refer to the doc for more reference

Thanks

Thanks for the clarification. I tried google search and did not find that but good to have definitive answer. I’ll mark this as Solution by way of indicating its the “Accepted Answer” but its not really a solution:)

I don’t suppose there is any workaround to this? I don’t want to put really long delays but I’m hoping to have a way to add small delay to avoid race conditions.

Hi Steve,

I understand your problem and I think there is a solution available for it.

You could make use of the Scheduled Events to achieve a delayed execution of your callback function.

I have used this effectively in many of my apps so far.

Regards,
Arun Rajkumar

3 Likes

You have probably addressed this now but I wanted to post a simple and crude solution that worked for me as I need a short delay after an event fired before I did the next thing. Scheduled events work but you can not schedule event less than 5 minutes in the future so are no good if you just want a short delay. Remember to add async to the wrapper function. Hope this helps anyone else looking for a solution.

async function yourFunction() {
    
  console.log('now')

   function sleep(ms) {
     return new Promise(resolve => {
       let startTime = Date.now()
       let currentTime = null
       do {
        currentTime = Date.now()
       } while (currentTime - startTime < ms);
       resolve()
      });
    }

    await sleep(5000)

    console.log('5 secs later')

}
2 Likes

Thank you. That’s a good solution but I hate to implement a tight loop and load up server compute. But its only for a second or two and its not my server :wink:

Its too bad that freshworks does not allow the setTimeout function which is much more efficient for their servers.

Totally agree. Its definitely crude and I wouldn’t use it if there was an alternative or for much longer than a few of seconds.