Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to pass a callback with intended argument [duplicate]

Tags:

javascript

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.

like image 861
Alexander Soare Avatar asked Mar 04 '23 08:03

Alexander Soare


2 Answers

setTimeout accepts a function as an argument:

setTimeout(() => log("myChoice"), 2000)
like image 143
Clarity Avatar answered Mar 09 '23 05:03

Clarity


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)
like image 24
ISD Avatar answered Mar 09 '23 05:03

ISD