0

I want to Implement a function which can run a given function after a delay.

Arguments:

  • callback: the function to execute after the delay
  • delay: number of milliseconds to wait
  • data: the one (and only) argument to pass to the callback

And this was my code

let cb = function(x) {
  console.log(x);
};

const doShortly = function(callback, delay, data) {
  let result = setTimeout(callback(data), delay);
  return result;
};

console.log(doShortly(cb, 500, 'hi'));

I get TypeError [ERR_INVALID_CALLBACK] when I run the code. May I know how to fix this. TIA.

ras
  • 1
  • Your result variable is wrong. The setTimeout function takes a callback too. But you are running the callback within setTimeout. –  Nov 19 '21 at 17:48
  • This is a duplicate, please look at this post/answer: https://stackoverflow.com/a/39914235/944670 – JW_ Nov 23 '21 at 08:36

1 Answers1

0

You can use setTimeout or setInterval for that directly. All the params after the delay param, will be passed to the callback function in the same order :)

let cb = function(x) {
  console.log(x);
};

const doShortly = function(callback, delay, data) {
  let result = setTimeout(callback, delay, data);
  return result;
};

console.log(doShortly(cb, 500, 'hi')); // or: setTimeout(cb, 500, 'hi')

Max
  • 1,996
  • 1
  • 10
  • 16