Question about using functions as arguments

In the video ‘Functions as Arguments and Timeout’ @ivan passed in the function name without the parentheses as an argument to another function.

wo_paren

2seconds

I found that passing it in with parentheses triggers the function immediately and produces unexpected results.

with_paren

immediate

I’m wondering, because of this behaviour, if there’s a way to pass functions as attributes if they themselves take attributes.
For example:

with_attrib

immed_with_pic

The text displays immediately to the screen without the 2 second delay.

setTimeout(textToScreen, 2000, "but this is ok"))

after the delay can be as many parameters as needed

1 Like

Thanks for that @rbondi. It does work, but I found that by itself it also overwrites the image.
After a bit of mucking around I got the desired effect by giving the elements an id.

fixed

When the page loads:

before2

After 2 seconds:

after2

I have this kind of code:

function doNumberOfTimes(toDo){
for(n = 0; n < 4; n++){
toDo();
}
}

function consoleAlert(){
  console.log("alert!");
}

doNumberOfTimes(consoleAlert);
setTimeout(doNumberOfTimes(consoleAlert), 5000);

The problem is that the last 2 lines trigger at the same time, while one of them should trigger 5 times after. Any ideas how to deal with this?

you are calling doNumberOfTimes, not passing it to setTimeout, so create a function inline to pass that calls it.

setTimeout(() => doNumberOfTimes(consoleAlert), 5000);

1 Like

Well that is an interesting and unseen way to do it. Thanks.