0

I am trying to create a small application that closes over the delay function and defines a new function using a callback and a wait time. I then wanted to use this newly created inner setTimeout function to take a single parameter that would be run on the callback after the wait time.

function addTwo(num) {
  return num + 2
}

const delay = (callback, wait) => {
  return setTimeout((value) => callback(value), wait)
}
var delayAddByTwo = delay(addTwo, 100)
console.log(delayAddByTwo(6))
// expected result 8 
// actual result --- Uncaught TypeError: delayAddByTwo is not a function

As far as I can tell after the delayAddByTwo = delay(addTwo, 100) the only parameter left to create is the value passed to callback inside the 'inner' setTimeOut function. What am I missing about closure in this example?

1
  • 1
    setTimeout will return its id Commented Jan 30, 2020 at 2:54

3 Answers 3

2

You need to replace var delayAddByTwo = delay(addTwo, 100) by var delayAddByTwo = (num) => { delay(() => {addTwo(num)}, 100);}

function addTwo(num) {
  console.log(num + 2)
  return num + 2
}

const delay = (callback, wait) => {
  setTimeout(callback, wait)
}
var delayAddByTwo = (num) => {
  delay(() => {addTwo(num)}, 100);
}
console.log(delayAddByTwo)
delayAddByTwo(6)
// expected result 8 
// actual result --- Uncaught TypeError: delayAddByTwo is not a function

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

1 Comment

You can use setTimeout(callback, wait) instead of setTimeout((value) => callback(value), wait) - value isn't being used
0

You need to make delay return another function which accepts n. This n represents the number which will be passed into addTwo (ie the callback). setTimeout by default will return its timeoutID, so, instead, you can return a Promise, which resolves to the result of calling addTwo with n. In order to get your result from the Promise, you can await it within an async function.

See example below:

const addTwo = num => num + 2;
const delay = (callback, wait) => n => new Promise(res => setTimeout(res, wait, callback(n)));

(async () => {
  const delayAddByTwo = delay(addTwo, 1000);
  const res = await delayAddByTwo(6);
  console.log(res);
})();

Above I have used the third argument of setTimeout, which will be used as the first argument of the callback and passed to res.

Comments

0

Change

var delayAddByTwo = delay(addTwo, 100)

To

const delayAddByTwo = delay => (addTwo, 100)

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.