Search code examples
javascriptangularjswebangularjs-scopetimeout

Angular JS $timeout and $scope function communication


I just find strange(for me) thing in angularjs. Why do these parts work differently?

Timeout is Working (alert after 8sec)

$scope.testfun = function(){
    alert(2);
}
$scope.activate = function(h,m,s){
    if(h != 0 || m != 0 || s != 0) $timeout($scope.testfun, 8000);
}

Timeout is NOT Working (alert momentally)

$scope.testfun = function(){
    alert(2);
}
$scope.activate = function(h,m,s){
    if(h != 0 || m != 0 || s != 0) $timeout($scope.testfun(), 8000);
}

Difference in $scope.testfun and $scope.testfun()


Solution

  • You need to write timeout function like below::

    $scope.testfun = function() {
        alert(2);
    }
    
    $scope.activate = function(h,m,s) {
        if (h != 0 || m != 0 || s != 0) {
          $timeout(function () {
            $scope.testfun();
          }, 8000);
        }
    }