What's the difference between using setTimeout()
so
setTimeout(()=>this.logicaRotacao(), 3000)
And so?
setTimeout(this.logicaRotacao(), 3000)
What's the difference between using setTimeout()
so
setTimeout(()=>this.logicaRotacao(), 3000)
And so?
setTimeout(this.logicaRotacao(), 3000)
The first one passes an anonymous function that calls this.logicaRotacao()
, then at the appropriate time (every 3 seconds in this example) it will be called by the engine of JS, since you set this action through the function setTimeout()
. This is a callback mechanism. see date notation or arrow . And more details and use examples . And another canonical question on the subject .
The second runs the this.logicaRotacao()
function and passes its result to the setTimeout()
function run every 3 seconds. If what is returned by this.logicaRotacao()
is not a function it will give an error or unexpected result.
This could be correct too:
setTimeout(this.logicaRotacao, 3000)
In this case you are not calling the function and passing this function. Without the parentheses, it is not a call, but only the address of the function. It's even more accurate than the first option in this example because your code has an extra indirection , it's passing a function that calls a function without doing anything else, then passes function that will call logo.
The function documentation indicates 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 executing the function.
Note down the time to show each one. The first takes the time set, the second does immediately.
function logicaRotacao() {
console.log("ok");
}
setTimeout(()=>this.logicaRotacao(), 5000);
function logicaRotacao() {
console.log("ok");
}
setTimeout(logicaRotacao(), 5000);
The first argument of setTimeout is a callback function.
In setTimeout(()=>this.logicaRotacao(), 3000)
you are defining a function using the arrow function
notation, this function when invoked executes this.logicaRotacao()
In setTimeout(this.logicaRotacao(), 3000)
you are executing the this.logicaRotacao
function and passing it back to setTimeout
. Unless the return of this.logicaRotacao
is a function, this will not work, you have to pass the function itself, not the return of it. The right would be setTimeout(this.logicaRotacao, 3000)