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
- I'm not actually concerned with logging things after 2 seconds. This is a prototype question for my more general question of how to tell javascript which parameters I want a function to use when it's called.
- Bonus question: How could I have phrased my question title better? Is "callback" even the right word here?
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.