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);
};
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);
};
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.
Try something like:
setTimeout(cb, ms, msg);
By putting msg
on the end it'll automatically pass msg
into cb
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);