根据视频时间更改变量

时间:2016-08-19 16:35:29

标签: javascript angularjs arrays conditional traversal

我需要在视频中显示“标题”,但我不能使用vtt文件提供的内置标题来表示我的情况。我创建了一个存储键,值对(时间,标题)的数组。每次更新视频时间时,我都会遍历该数组,并查找哪个标题符合当前时间。这个解决方案有效,我没有任何问题(性能或其他方面),但它只是对我来说是蛮力,我希望有人可以帮助我改进我所拥有的或引导我走向更优雅的解决方案。任何评论或批评都表示赞赏。

 //this function is called whenever video time is updated
    this.onUpdateTime = function(currentTime, totalTime) {

        this.currentTime = currentTime;
        this.totalTime = totalTime;

        /*the for statement traverses the array chapters which contains 
        [{"time": X,"caption": "XYZ"},...]*/

        for (var i = 0; i < $scope.chapters.length; i++) {

            /* the first if statement checks if (i is not the same as 
            chapters.length (this was done to prevent an off by one error) and the time of 
            the video is greater than or equal to time at chapters[i] and the time of the 
            video is still less than time at the next chapter marker chapter[i+1]*/

            if (i != $scope.chapters.length - 1 && currentTime >= $scope.chapters[i].time && currentTime < $scope.chapters[i + 1].time) {

                /*set the caption to the value from chapters[i].caption*/

                $rootScope.caption = $scope.chapters[i].caption;

                /*I have never used $scope.$apply but it seemed to be needed to get the caption to display in my view*/

                $scope.$apply(); {

                    /*break the for loop so that it does not needlessly loop through the rest of the array after finding a match*/
                    break;
                }

                /*this if statement if for when i is equal to chapters.length -1, it is the final value in the array so it does 
                not check against the "next value" like the previous if statement does because there is not next value*/

            } else if (currentTime >= $scope.chapters[i].time && i == $scope.chapters.length - 1) {

                /*set the caption to the value from chapters[i].caption*/

                $rootScope.caption = $scope.chapters[i].caption;

                /*I have never used $scope.$apply but it seemed to be needed to get the caption to display in my view*/

                $scope.$apply(); {

                    /*break the for loop so that it does not needlessly loop through the rest of the array after finding a match*/
                    break;
                }

                /*if there is not chapter marker at the current time*/
            } else {

                /*set the caption to a blank value because no match was found therefore there is no caption*/
                $rootScope.caption = "";
                $scope.$apply();
            }
        }
        // console.log("onUpdateTime function, currentTime is: " + currentTime);
        // console.log("onUpdateTime function, totalTime is: " + totalTime);
    };

0 个答案:

没有答案