2

There are two functions hello1() and hello2().

function hello1(){
    console.log('hello1');
}

function hello2(){
    console.log('hello2');
}

setTimeout(hello1, 3000);
setTimeout(hello2(), 3000);

In setTimeout(hello1, 3000);, it print "hello1" after delay 3 seconds.

But in setTimeout(hello2(), 3000);, it print "hello2" immediately.

I think it's because it must use function name in setTimeout.

What if I want to execute a function with parameters after delay 3 seconds like hello(1)?

Because I want to deliver parameters into function so I can't just only use function name in setTimeout like setTimeout(hello1, 3000);

Larry Lu
  • 1,609
  • 3
  • 21
  • 28

1 Answers1

3

When you use parenthesis for the function in setTimeout it is executed immediately.

To use function with parameters, you can use anynomous function as timeout function and call your function inside it.

setTimeout(function() {
    hello(1, 'param');
}, 3000);
Tushar
  • 85,780
  • 21
  • 159
  • 179