AngularJS $interval should dynamically in-/ decrease

后端 未结 1 1454
借酒劲吻你
借酒劲吻你 2021-01-23 02:47

i just want to use $interval(anyFunction(){}, 1000); But value of 1000 should be variable, too. If i change it by defining a variable, the interval won\'t change on the view.

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-23 03:40

    You need to use $timeout:

    $scope.food = 0;
    var farmInterval = 1000;
    var shouldStop = true;
    
    $scope.startFarming = function () {
        console.log('farming started...');
        shouldStop = false;
        var loop = function () {
            if (!shouldStop) {
                $scope.food += 1;
                $timeout(loop, farmInterval);
                //defers another call to this function in a timeout
                //on each "iteration" like this -actually it's not
                //an interation- you can control what interval time to assign
            }
        };
    }
    
    $scope.stopFarming = function () {
        shouldStop = true;
    }
    
    $scope.increaseFarmInterval = function () {
        console.log(farmInterval);
        if (farmInterval > 100) {
            console.log('Increased by 50');
            farmInterval -= 50;
        } else {
            console.log('maximum reached.');
        }
    }
    

    Notice how I converted the $timer in a chain of $timeout calls. This is not only good practice to alter the interval, but also was the only way a script could implement setInterval when a browser implemented only setTimeout those days.

    Most of the code is already yours, but I modified the $timer-related logic and don't use $timer anymore, so you must inject $timeout instead (or also - it depends if you're using $timer somewhere else in the controller, or not).

    So the logic was changed: you don't kill a timer. Instead you prevent a new $timeout iteration occurs, since -if you look closely- each iteration is created explicitly after the loop's central logic.

    0 讨论(0)
提交回复
热议问题