1

Why is that when using $timeout in Angular JS that is inside function like the following, works fine.

var mytimeout = $timeout(function(){
    console.log("MyTimeout Executed");
},2000);
mytimeout.then(
    function() {
        console.log( "mytimeout resolved!", Date.now() );
    },
    function() {
        console.log( "mytimeout rejected!", Date.now() );
    }
);

but when I use $timer with a function inside $scope it does not work, like this:

$scope.myFunction = function(){
   console.log("MyTimeout Executed");
}; 

var mytimeout = $timeout($scope.myFunction(),2000);
mytimeout.then(
    function() {
        console.log( "mytimeout resolved!", Date.now() );
    },
    function() {
        console.log( "mytimeout rejected!", Date.now() );
    }
);

and recieve this error:

TypeError: undefined is not a function
    at http://0.0.0.0:3000/assets/angular.js?body=1:14015:28
    at completeOutstandingRequest (http://0.0.0.0:3000/assets/angular.js?body=1:4301:10)
    at http://0.0.0.0:3000/assets/angular.js?body=1:4602:7 angular.js?body=1:9779
(anonymous function) angular.js?body=1:9779
(anonymous function) angular.js?body=1:7217
(anonymous function) angular.js?body=1:14018
completeOutstandingRequest angular.js?body=1:4301
(anonymous function) angular.js?body=1:4602

1 Answer 1

7
var mytimeout = $timeout($scope.myFunction(),2000);

This is your problem. Remove the () from the myFunction(). You need to pass a function reference, not call the function and take the result (which in this case would be undefined) and then pass that to $timeout.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.