apdm
apdm

Reputation: 1330

Why isn't $timeout working when I pass a predefined function as the first argument?

The following executes immediately and ignores the timeout entirely

var print = function(){
console.log('hey');
}
$timeout(print(), 2200);

But this works perfectly fine

$timeout(function(){console.log('hey')}, 2200);

Why can't I use a variable that contains the function?

Upvotes: 1

Views: 49

Answers (6)

Robba
Robba

Reputation: 8324

There are already a few answers that show how to fix it, but to answer your question:

Why can't I use a variable that contains the function?

The thing is, you can, but that's just not what you're doing. When you create a function like this:

var print = function(){
    console.log('hey');
}

You end up with a variable named print that points to a function. You can now do two things with it

  1. pass it along as a function
  2. invoke it and get it's result

While it's not immediately apparent, every function in JavaScript always returns a result. Your function is equivalent to this:

var print = function(){
    console.log('hey');
    return undefined;
}

So when you're using a timeout you need a function as the first parameter. Since invoking your print() function yields a result (of undefined), this is not what the timeout function requires.

So to recap:

Correct

$timeout(print, 2200); // Pass the function as an argument

Incorrect

$timeout(print(), 2200); // Pass the value undefined as an argument

Upvotes: 0

Lahar Shah
Lahar Shah

Reputation: 7674

Use only print

var print = function(){
    console.log('hey');
}
$timeout(print, 2200);

Here is working example with jQuery function setTimeout()

var print = function(){
  console.log('hey');
}
setTimeout(print, 2000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

M B
M B

Reputation: 2326

$timeout(print, 2200);

Remove the paranthesis from the function

Upvotes: 0

lealceldeiro
lealceldeiro

Reputation: 14998

var print = function(){
console.log('hey');
}
$timeout(print, 2200);

Upvotes: 1

Dave Cooper
Dave Cooper

Reputation: 10714

The first argument to the $timeout constructor is a function, not an invocation of a function.

Change it to $timeout(print, 2200); and that should work fine :)

You can read more about the $timeout service here: https://docs.angularjs.org/api/ng/service/$timeout

Hope that helps!

Upvotes: 2

Isma90
Isma90

Reputation: 661

This is incorrect:

var print = function(){
console.log('hey');
}
$timeout(print(), 2200);

The correct form to pass the function is:

var print = function(){
console.log('hey');
}
$timeout(function(){
    print()
}, 2200);

Because $timeout need a function in first argument.

Can you Read this in Angular Doc

Upvotes: 1

Related Questions