0

I want the browser to wait for 3 seconds before executing the next line of code.

$timeout(3000); in script is not seeming to do the trick. Am I doing anything wrong here.

I use it inside a $scope function

app.expandController = function ($scope,$interval, $timeout) {

    $scope.nextLevel = function () {

            //stop numbers
            $scope.StopTimer();

            $timeout(function(){return true;},3000);

            //restart timer with new numbers
            $scope.StartTimer();

            $scope.thresholdwatch == false
        }
}

and I split controller file by passing $scope and $timeout to another function

app.controller('myCtrl', function ($scope, $interval, $timeout) {


    app.expandController($scope, $interval,$timeout);

});

3 Answers 3

2

If you are using $timeout you need to place your next executing code in timeout callback. But a simple hack with vanila js would be,

function sleep(ms) {
  var dt = new Date();
  while (Date.now() - dt.getTime() <= ms) {}
  return true;
}

console.log('timer start');
sleep(3000);
console.log('Printing after 3000ms');

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

Comments

2

I think you get the idea about $timeout in AngularJS or generally JS incorrect. Both of the below examples will not work.

$timeout(function(){return true;},3000); 
$timeout(3000);

$timeout is a non-blocking function so calling it will not stop JS from running the code below it. In Javascript and AngularJS, there is no truly sleep function (a NodeJS lib for sleep is actually the C++ binding for it, and therefore, not applicable to client-side app using AngularJS). Instead, to make sure that your code will be run after a specific amount of time, you put it inside the the $timeout function:

$timeout(function(){
   //code need to be delayed must be in here
}, TIME_TO_WAIT_FOR); 

Comments

1

The usage of $timeout is wrong. Use like this:

$timeout(function(){
  // Do something in timeout
}, 3000);

1 Comment

$timeout(function(){return true;},3000); This is still not causing the browser to wait for 3 seconds.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.