BobbyA
BobbyA

Reputation: 2260

Why does $timeout require functions with parameters to be wrapped in anonymous functions?

I'm having trouble using $timeout, and stumbled upon this solution on this site:

How to run function with parameters using $timeout in AngularJS?

While that answered the "how", it didn't address the "why". When you want to defer the execution of a function that requires parameters, using $timeout, why must it be wrapped in an anonymous function, and why is this also not necessary for parameterless functions?

Upvotes: 1

Views: 234

Answers (3)

floribon
floribon

Reputation: 19193

$timeout takes a function in parameter, and will call this function with no parameters.

For instance $timeout(foo) will result in foo() being called like this with no parameter, even if foo is supposed to work on some parameters.

So what people usually do is wrap the call of foointo an anonymous function to be faster, but it can totally be a named function such as in this example:

function foo(name) { alert('hello ' + name) }
function fooBar()  { foo('bar') }

$timeout(fooBar)
// or, as this is totally equivalent
$timeout(function() { foo('bar') })

Now for your information Javascript allows you to bind parameters to a function with the keyword bind. So our examples above are also equivalent to this:

$timeout(foo.bind(null, 'bar'))

Indeed, foo.bind(null, 'bar') is also a new function equivalent to fooBar, it is foo where this is set to null (since it is not used anyway) and the parameter name is forced to "bar".

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 692151

Because when the callback function is finally called, it's called without any argument.

Upvotes: 1

Michel
Michel

Reputation: 28359

Why does $timeout require functions with parameters to be wrapped in anonymous functions?

$timeout does not require functions to be wrapped in anonymous functions. It's just that $timeout is not a friend of your function, so to speak, and will not pass arguments to the function you give him. Therefore, it makes no sense to give him a function that works with arguments.

Upvotes: 0

Related Questions