serv-inc
serv-inc

Reputation: 38177

setTimeout(function() {doSth();}, 3) vs setTimeout(doSth, 3)?

Of the above, which is preferable? Why would you use

setTimeout(function() { anotherFunction(); }, 3);

instead of

setTimeout(anotherFunction, 3);

?

For example, the documentation for the testing tool jasmine uses an anonymous inner function without parameters. But why? What are the advantages/disadvantages of the anonymous function style?

Upvotes: 2

Views: 74

Answers (1)

David
David

Reputation: 141

The primary advantage is the scope where the variables exists.

Take this two scenarios for example:

Scenario 1

function foo() {
  let element = document.getElementById('bar');
  element.classList.add('some-effect');
  setTimeout(function() {
    element.classList.remove('some-effect');
  }, 1000);
}

Scenario 2

function foo() {
  let element = document.getElementById('bar');
  element.classList.add('some-effect');
  setTimeout(removeEffect, 1000);
}

function removeEffect() {
  let element = document.getElementById('bar');
  element.classList.remove('some-effect');
}

In the first scenario you have access to the element because you are inside the scope of the foo function.

In the second one you have to search again the element in the removeEffect function because the scope has changed.

If you need to reuse variables of the scope where you are working, use the code of the first scenario. If you don't really need the variables in the scope or want to make the function reusable, use the second scenario

Upvotes: 4

Related Questions