1

I have a long loop for, when I ty to turn on annother controller from the the browser on clicking on annother link, the first process continue executing and I can't access to the second controller, is there any solution, I try this code but it dosen't give the result

    $scope.exit = false
    $scope.$on("$destroy", function(){

            $scope.exit = true




        });

        for (var x = 0; x < myArray.length; x++) {



            if($scope.exit)
                break;

              //my code

           }
user2285831
  • 419
  • 1
  • 5
  • 18
  • 1
    Unfortunately Javascript isn't multitasking, so that if you're inside that loop, the `$scope.exit` doesn't become `true` until the end of the loop. Intensive loops and operations shouldn't be performed as _synchronous_ action, as they can block the execution of the rest of the code. What is that loop used for? Can you manage to execute it somewhere else or in an asynchronous way, or in the worst case make a loader appear on page so that the user can't switch page? – Luca De Nardi Nov 03 '17 at 11:01
  • It's for calculation, and the user should exit either if the calculation dosen't end, what do you means with synchronous action ? unfortunately, i can't execute the code somewhere else – user2285831 Nov 03 '17 at 11:06
  • [Sync vs Async code](https://stackoverflow.com/questions/16336367/what-is-the-difference-between-synchronous-and-asynchronous-programming-in-node). Unfortunately (or fortunately) that is Javascript works. – Luca De Nardi Nov 03 '17 at 11:11
  • Is there any way that i write my for loop asynchrnously like this database.query("SELECT * FROM hugetable", function(result) { console.log("Query finished"); }); console.log("Next line"); – user2285831 Nov 03 '17 at 11:25
  • It depends on what you have to do in that loop. There are many ways, like an _async Ajax_ call to the server (demand the heavy operations to the server and get back to Javascript with the result), a _webworker_ (an asynchronous service executed in parallel with your website), it really just depends on what you have to do inside the loop. – Luca De Nardi Nov 03 '17 at 11:27
  • inside the loop i call a web service like this : api.PostWs({url: "myUrl"}, id).then(function (response) { if (response.success) { $scope.myVar = response.val } }); – user2285831 Nov 03 '17 at 11:30
  • And where's the loop? Can you do it on the server? – Luca De Nardi Nov 03 '17 at 11:39
  • this is why, i don't whant to execute the loop on the server, to load the first part of data, then in the controller i execute the WS of calculation I don't whant to use loader and the loop on the server, because it take much time to load the view and the data – user2285831 Nov 03 '17 at 11:45
  • 1
    You then want to take a look on how to implement an async loop [here](https://stackoverflow.com/questions/4288759/asynchronous-for-cycle-in-javascript) – Luca De Nardi Nov 03 '17 at 12:38

0 Answers0