I want to print a string of my choice to the console after 2 seconds.
This prints 'Hello'
to the console after 2 seconds:
function log() {
console.log("Hello")
}
t = setTimeout(log, 2000)
But I didn't get to choose which string gets printed. It was hardcoded in the function.
This next bit of code does print 'myChoice'
to the console but it does it immediately, rather than waiting 2 seconds:
function log(st) {
console.log(st)
}
t = setTimeout(log("myChoice"),2000)
That's because, as I understand, setTimeout wants me to feed it a function.
How do I feed the log
function to setTimeout and also tell it that when it runs it I want it to use whatever string I give it?
Notes
Edit: Some people marked this as a duplicate, and indeed the question title is pretty much the same as another thread. But, the other question's body seems to have anchored all the answers to a particular way of solving the problem, ie using an intermediate function. I think that the answer I got here is the best one given the question title.
setTimeout
accepts a function as an argument:
setTimeout(() => log("myChoice"), 2000)
Maybe a fabric function?
function log(str) {
console.log(str)
}
// As fn - function, next arguments
// Any amount of args
function pass_args(fn, ...args) {
return () => {
fn(...args)
}
}
t = setTimeout(pass_args(log, "My arg"),2000)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With