Mark
Mark

Reputation: 656

JS: timeout over function execution

I have a function which returns a callback. Its execution time may vary. Is there a way to set a timeout callback over it? Or kill the function and go over with the code?

Upvotes: 0

Views: 69

Answers (1)

Sudhir
Sudhir

Reputation: 126

Its the game of timeouts.
Here is an example using setTimeout and Promise

function executeWithin(targetFn, timeout) {
  let invoked = false;
  return new Promise((resolve) => {
    targetFn().then(resolve)
    setTimeout(() => {
      resolve('timed out')
    }, timeout)
  })
}

executeWithin(
  // function that takes 1sec to complete
  () => new Promise((resolve) => {
    setTimeout(() => {
      resolve('lazy fn resolved!')
    }, 1000)
  }),
  2000 // must invoke callback within 2sec
).then(console.log) 
// => lazy function is finally done!

executeWithin(
  // function that takes 3s to complete
  () => new Promise((resolve) => {
    setTimeout(() => {
      resolve()
    }, 3000)
  }),
  2000 // must invoke callback within 2sec
).then(console.log) 
// => timed out

Upvotes: 1

Related Questions