当我尝试取消并重新启动时,Angular js $ timeout无法正常工作

时间:2016-12-06 11:58:22

标签: javascript angularjs timeout

我正在尝试使用角度js $超时功能创建问题幻灯片,我能够实现它并且它工作正常,但是当我尝试刷新幻灯片以便它可以再次启动时刷新仅适用于第一张幻灯片,因为其他幻灯片将无法使用超时延迟时间 这是我的代码,主要功能和召回功能。

    $scope.callTime = function() {
        q_len = questions.length;
            $timeout(function () {
                //checking if the question index is still valid
                if (q_indy < q_len) {
                    slides = questions[q_indy].pictures;
                    len = slides.length;
                    console.log(indy);
                    $scope.currentQuestion = questions[q_indy];
                    f_time = parseInt(slides[indy].time_frame);
                    //getting the specific time needed to run this particular slide
                    r_time = f_time - initialTime;
                    if (indy < len) {
                        f_time = parseInt(slides[indy].time_frame);
                        var interval = slides[indy].picture_url;
                        indy++;
                        console.log(q_indy + " " + indy + " " + r_time);
                        //changing to the current picture so it can run for the given time
                        $scope.image = $scope.url.url + interval;
                        if (indy == len) {
                            //checking if the question's slides is out of index so the next question should be loaded
                            q_indy++;
                            indy = 0;
                            initialTime = f_time;
                            console.log(q_indy + " " + indy + " " + r_time);
                            $scope.callTime();
                        }
                        else {
                            //if the slide index is active the next slide should be loaded then
                            initialTime = f_time;
                            $scope.callTime();
                        }
                        //console.log($scope.url.url + interval);
                    }
                }
            }, r_time);
            //time();
        }
    $scope.refresh = function () {
        $timeout.cancel($scope.callTime);
        q_indy = 0;
        indy = 0;
        initialTime = 0;
        r_time = 0;
        len = 0;
        q_len = 0;
        $scope.callTime();
       var e = document.getElementById('myTune');
        //e.pause();
        e.currentTime = 0;
        //e.play;
    };

1 个答案:

答案 0 :(得分:1)

您需要保存调用$timeout时返回的值,并将该值传递给$timeout.cancel()。相反,你传递的是你用来创建超时的函数,而这个函数不是$timeout.cancel()所知道的。

var timer = null;
$scope.callTime = function() {
    q_len = questions.length;
    $timeout.cancel(timer); // You probably also want to cancel here
    timer = $timeout(function () {
          // ... rest of your code here ...
        }, r_time);
        //time();
    }
$scope.refresh = function () {
    $timeout.cancel(timer);
    // ... and rest of your code here ...
};