What is the difference between these uses of the setTimeout() function?

Asked

Viewed 170 times

3

What’s the difference between using the setTimeout() thus

setTimeout(()=>this.logicaRotacao(), 3000)

and so?

setTimeout(this.logicaRotacao(), 3000)

2 answers

7


The first passes a anonymous function what call this.logicaRotacao(), then at the appropriate time (every 3 seconds in this example) it will be called by engine of the JS, since you setou this action through the function setTimeout(). This is a mechanism of callback. see the close or arrow notation. And yet more details and example of use. And another canonical question on the subject.

The second executes the function this.logicaRotacao() and passes its result to the function setTimeout() run every 3 seconds. If returned by this.logicaRotacao() is not a function will give an error or unexpected result.

This could be right too:

setTimeout(this.logicaRotacao, 3000)

In this case you are not calling the function but passing this function. Without the parentheses it is not a call, but picking up only the address of the function. It is even more correct than the first option in this example because your code has a indirect extra unnecessarily, is passing a function that calls a function without doing anything else, then passes function that will call soon.

To job documentation indicates well that it expects a function. There is a huge difference between passing a function and calling a function. Read the link above to better understand this delay in the execution of the function.

Notice below the time to show each one. The first takes the time placed, the second makes immediately.

function logicaRotacao() {
    console.log("ok");
}
setTimeout(()=>this.logicaRotacao(), 5000);

function logicaRotacao() {
    console.log("ok");
}
setTimeout(logicaRotacao(), 5000);

I put in the Github for future reference.

6

The first argument of setTimeout is a callback function.

In setTimeout(()=>this.logicaRotacao(), 3000) you are setting a function using the notation arrow function, this function when invoked executes this.logicaRotacao()

In setTimeout(this.logicaRotacao(), 3000) you are running the function this.logicaRotacao and passing her return to setTimeout. Unless the return of this.logicaRotacao be a function, it will not work, you have to pass the function itself, not the return of it. Right would be setTimeout(this.logicaRotacao, 3000)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.