0

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?

2
  • Why not use setTimeout() to call a function in order to read the response asynchroniously Commented Jul 5, 2021 at 12:38
  • @AlexandroPalacios I need something like ajax's timeout Commented Jul 5, 2021 at 13:10

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.