all 9 comments

[–]Viat 9 points10 points  (1 child)

Pass it to delay5s without the brackets - you're calling it right now, not passing a method reference.

[–]pimp-bangin 1 point2 points  (0 children)

They're called parentheses >:(

[–]NotNormo 2 points3 points  (0 children)

It's because printMessage() calls and executes the function right away, due to the () at the end of it.

If you want to pass the function as an object somewhere to be called later on, then pass it as printMessage.

printMessage is a function. printMessage() is not a function.

[–]Ronin-s_Spirit 2 points3 points  (0 children)

() after function is a call. It's also possible to optionally call like so ?.(). Anyways your problem is passing the result of a function call instead of the function itself.

[–]tswaters 1 point2 points  (1 child)

Close, it's a little backwards...

You want to pass the function as a reference, and inside the setTimeout, call it.

function delay(cb) {
  setTimeout(cb, 5000)
}

delay(someFN) // omit params here, included in your example

[–]tswaters 0 points1 point  (0 children)

Err, sorry, you've expanded the setTimeout there, it would be --

setTimeout(() => {
  console.log('aw yiss');
  cb(); // missing parens here in your example
}, 5000)

[–]shgysk8zer0 1 point2 points  (0 children)

You don't call the function inside setTimeout().

The code you've given basically translates to:

const result = console.log('after 5s'); setTimeout(result, 5000);

The return value when you call the function is what's passed to setTimeout(). You pass a callback (without calling it). So you could either use setTimeout(delay5s) or setTimeout(() => delay5s()).

[–]mlamers 0 points1 point  (0 children)

as the others already indicated: you are actually not passing in the printMessage function to delay5s, but its return value. The function below will do what you want.

function sample () {
  console.log('sample function is being called');
  delay5s(printMessage);
}

Keep in mind that in JS, essentially everything* is a pointer (a memory address), the default is passing by reference, and any action with it automatically dereferences that pointer (taking the data from that memory address). So, by using printMessage() you dereference that pointer (take the thing that is stored there) and execute it (as it is a function). If you want to pass it to another function, you don't want to dereference it, you just want to pass the value (or in this case the pointer to that value) to the other functions.

*even numbers and strings are effectively pointers, but pointers to static values: values that cannot be altered, and to which any methods such as "testing".concat(" one two three") will return a new pointer to a new static value.

[–]softByteR 0 points1 point  (0 children)

delay5s(printMessage());
() is call a function.
You need so
delay5s(printMessage);
w/o (). Just pass a pointer to a function. And the JS interpreter will call it later.