$timeout
is a wrapper for setTimeout
that gets mocked out during testing. @MarkRajcok is completely right about about why using it as a blocking method doesn't work. Mark's solution would also solve your issue. But if it's not feasible to relocate your code, there is still good news!
$timeout
returns a promise (see $q
), so you can actually just chain together what you want:
$timeout( tempFunc, $scope.sync.getDelay() ).then( function() {
console.log("I'm called only after the timeout.");
$scope.sync.releasePrivilege();
});
console.log("But I get called immediately.");
And this should work just fine, should you fancy. It still doesn't block. It just ensures that the function within the then
call is executed only after the promise is resolved, that is only when the timeout has completed and your method has been called.
Additionally, your function can return data, if needed. So if tempFunc
returned a Boolean value that indicated success, you could also access it:
$timeout( tempFunc, $scope.sync.getDelay() ).then( function( result ) {
if ( result ) {
$scope.sync.releasePrivilege();
} else {
// handle the error
}
});
And there was much rejoicing. Yay.
Just as a note: doing a sleep in a browser would be very bad - it'd lock the UI. Asynchronous execution is what makes the web an awesome platform!