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);
};
0

3 Answers 3

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.

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

Comments

2

Try something like:

setTimeout(cb, ms, msg);

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

Comments

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?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.