JavaScript setTimeout(): Type Error on line callback is not a function at blob: callback is not a function

Viewed 501

I'm creating a delay function that accepts a callback and the wait time in milliseconds as parameters. delay should return a function that, when invoked, waits for the specified amount of time before executing. Here I'm using setTimeout() to set a timer before it executes the function.

function delay (callback, time) {
  function waitOnMe(...args) {
    return setTimeout(time);
  }
  return waitOnMe;
}

I use the following to test my code above:

let count = 0;
const delayedFunc = delay(() => count++, 1000);
delayedFunc();
console.log(count);                                                  // should print '0'
setTimeout(() => console.log(count), 1000); // should print '1' after 1 second

Then I get the following outputs and error message (note the third output is generated approximately 1 sec after the 2nd line appears as desired).

0
Type Error on line callback is not a function at blob: callback is not a function
0

I think I get this error is because the function is not returning from delay to execute the callback after the specified wait time, but I am not sure.

1 Answers

The first argument to setTimeout should be the callback and the second one is the delay. The rest of the arguments are used as arguments to the callback, which can be passed by spread syntax.

function waitOnMe(...args) {
    return setTimeout(callback, time, ...args);
}
Related