pv93
pv93

Reputation: 61

What is the purpose of putting a function in an otherwise empty function in javascript?

I am new to both Javascript and AngularJS, as well as web development, and while I was going through the Angular docs on directives, I came across this piece of code:

// start the UI update process; save the timeoutId for canceling
timeoutId = $interval(function() {
  updateTime(); // update DOM
}, 1000);

Why couldn't this just be written this way:

// start the UI update process; save the timeoutId for canceling
timeoutId = $interval(updateTime(), 1000);

Isn't it still a callback function this way? It's still a function within a function. What's the point of having a function in a function... in a function?

Upvotes: 0

Views: 44

Answers (2)

MarkNFI
MarkNFI

Reputation: 556

If you have a function like this:

timeoutId = $interval(function () {
    updateTime();
}, 1000);

there's not a lot of practical difference versus calling

timeoutId = $interval(updateTime, 1000); // Notice NO parens after "updateTime"!

Technically, the first version calls a function that does nothing but call another function, which means trivial amounts of extra overhead, not really worth worrying about.

One reason you might do something like this would be for code readability: it's arguably easier to "see" that the first version is passing a callback as the first argument to $interval(), since it's written out as a function. It won't make much difference in how fast your code runs, but it save you some development time if you or someone else needs to read and understand what's going on in the future.

Upvotes: 1

Tushar
Tushar

Reputation: 87203

Because, the function will be invoked immediately and the returned value will be assigned as the callback of the interval.

However, the function reference can be passed as the callback function which will be called after the specified time interval.

timeoutId = $interval(updateTime, 1000);
                                ^: Removed ()

Upvotes: 1

Related Questions