2

I'm trying to use setTimeout inside a function in which I provide the callback and the delay. I can't seem to get this to work.

Here's my code:

const timeout = function(cb, ms, msg) {
  setTimeout(cb(msg), ms);
};
GTA.sprx
  • 817
  • 1
  • 8
  • 24

3 Answers3

2

The first argument to setTimeout should be a function. You’re passing it the result of calling cb(msg). Try passing () => cb(msg) instead.

Note: Joshua’s answer is probably better because it avoids creating a new function. I always forget you can pass arguments that way.

ray
  • 26,557
  • 5
  • 28
  • 27
2

Try something like:

setTimeout(cb, ms, msg);

By putting msg on the end it'll automatically pass msg into cb

Joshua
  • 5,032
  • 2
  • 29
  • 45
0

You are calling the callback function inside setTimeout. First parameter of setTimeout is the reference to the function, which setTimeout will call automatically when provided time elapses. Also, to pass "msg" as parameter to callback function, you need pass it as third argument of setTimeout.

setTimeout(cb, ms, param1, param2, paramN);

How can I pass a parameter to a setTimeout() callback?

another_CS_guy
  • 682
  • 6
  • 7