0

Hello can you explain me what is the difference between setTimeOut(function, time) and setTimeOut(function(), time)

3 Answers3

0

Basically, either you define the function and later you pass it as the first parameter of setTimeout:

function onTimeout() {

}

setTimeout(onTimeout, 3000);

...or you give an anonymous function as parameter as you call setTimeout:

setTimeout(function() {
   // Do stuff
}, 3000);
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
0

The following examples will explain the difference:

Calling a defined function on timeout.

setTimeout(my_function, 1000);

function my_function() {
    alert("Time is up!");
}

Calling an anonymous function on timeout.

setTimeout(function() {
    alert("Time is up!");
}, 1000);

The first example calls a function that is already defined while the other runs code as a anonymous function procedurally. I use both depending on the need.

Timothy Wood
  • 487
  • 3
  • 10
0

The other two answers are correct, but just in case your question wasn't about anonymous functions but rather something like this

    function onTimeout(){
     console.log('foo');
    };

    setTimeout(onTimeout, 1000); // First form

    setTimeout(onTimeout(), 1000); // Second Form

The difference is that in the first form, the function onTimeout is called after 1 seconds, which is typically the desired outcome.

In the second form, on Timout is called immediately, and whatever that function returned is called after 1 seconds; in this case undefined would be called because console.log returns undefined. So the function would execute immediately and nothing would happen after 1 second.