Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularJS $timeout executing method instantly

I am using ionic framework and cordova-plugin-shake plugin to detect device shaking for one of my Android application, which is working fine. But the problem is after a shake I would like to disable this shaking detection for 30 second, for which I am trying to use $timeout like this:

$timeout($scope.watchForShake(), 30000);

But somehow for $timeout, no matter what the delay value is, $scope.watchForShake() is executed instantly.

I have also tried using setTimeout but the result is still the same.

like image 364
Waqas Avatar asked Mar 15 '23 15:03

Waqas


1 Answers

$timeout (and setTimeout) expect a callback function as its first parameter - that is the function that will execute after a certain time-out.

If you want the function .watchForTimeout to execute, then pass that function itself as a first parameter:

var callbackFn = $scope.watchForTimeout;
$timeout(callbackFn, 30000);

After 30 seconds, the function callbackFn will be invoked with no parameters: callbackFn().

In your case, you are invoking $scope.watchForTimeout right away, thus passing the return value of that function as the first parameter to `$timeout. So, what you are currently doing (incorrectly) is:

var returnVal = $scope.watchForTimeout();
$timeout(returnVal, 300000)
like image 80
New Dev Avatar answered Mar 24 '23 21:03

New Dev