Reputation: 5476
It is maybe incredibly easy but I couldn't solve what was going on.
function doSomething(a)
{
var num=10;
return setTimeout(
function(){ a(num); }, 1000);
}
The only thing that actually confuses me is the a(num) part. What actually it does?
Reminder: I really am asking because I'm not familiar with the javascript syntax.
Upvotes: 0
Views: 65
Reputation: 50493
When the function
doSomething()
is executed it is passed the parameter a
,
a
is also some function
that is then called when setTimeout()
expires after 1 second,
then calling the function
a()
passing the argument called num
// call doSomething() passing the test() function as an argument
doSomething(test);
// takes a number as an argument and shows an alert with that value
function test(number)
{
alert(number);
}
// takes a function as an argument that will perform a 1 second timeout then execute the function called a
function doSomething(a)
{
var num=10;
return setTimeout(
function(){ a(num); }, 1000);
}
Upvotes: 3
Reputation: 11245
setTimeout returns a timeoutID which can be used to cancel it using clearTimeout, so if you run doSomething a lot of times you will get different integer numbers which represent different timeoutID.
In your case a must be a function so you can call it using the parameter num
Example:
function doSomethingElse (justANumber) {
return justANumber + 1;
}
// Here you call your function
doSomething(doSomethingElse);
// or another special case
doSomething(function (justANumber) {return justANumber + 1;});
Upvotes: 0
Reputation: 65126
It calls the function referenced by the variable a
, using the value referenced by the variable num
as an argument.
Upvotes: 0