gpt4 book ai didi

javascript - 动态改变 Angular 的 $interval 延迟

转载 作者:行者123 更新时间:2023-11-30 15:06:09 26 4
gpt4 key购买 nike

我有一个旅游服务,它返回一个解析为旅游对象的 promise 。旅游对象有一些场景,每个场景都有一些热点。在主视图的 Controller 中,我有一个“私有(private)”_init() 函数,它等待游览解决,然后设置一些东西。

我正在使用一个应该无限地一个接一个地随机播放场景的间隔,但我希望场景之间的延迟基于当前事件场景的热点数量,例如有 2 个热点的场景应该持续 7.5 秒,有 1 个热点的场景应该持续 5 秒,等等。

这是我目前所拥有的:

var i = 0, ready, scenesCount, activeScene, duration, transition = null;
_init();

// Later on down...

function _init()
{
ready = false;

AlexaTourApi.getTour( null).then( function ( res) {
$log.log( 'AlexaTourController got tour', res);
$scope.tour = res;
scenesCount = $scope.tour.scenes.length;
activeScene = 0;

duration = (getActiveScene().hotspots.length + 1) * 2500;

ready = true;
transition = $timeout( _doTransition(), duration);
});
}

function _doTransition()
{
activeScene = (i++ % scenesCount);

duration = (getActiveScene().hotspots.length + 1) * 2500;

transition = $timeout( _doTransition(), duration);
}

编辑:

我根据 quirimmo 的建议实现了一些新代码:

function _init()
{
ready = false;

AlexaTourApi.getTour( null).then( function ( res) {
$log.log( 'AlexaTourController got scenes', res);
$scope.tour = res;
scenesCount = $scope.tour.scenes.length;
activeScene = 0;

duration = (getActiveScene().hotspots.length + 1) * 2500;

ready = true;
_resetInterval();
});
}

function _resetInterval()
{
if ( transition !== null) {
$interval.cancel( transition);
}

duration = (getActiveScene().hotspots.length + 1) * 2500;
transition = $interval( _doTransition(), duration);
}

function _doTransition()
{
activeScene = (i++ % scenesCount);
}

直到现在我才得到一个f is not a function异常。

最佳答案

您有一个 $timeout,它递归地调用内部的另一个 $timeout。等等。这意味着超时永远不会停止,因为它们会在内部执行的代码停止时停止。

使用 $interval 更改您的代码,并在开始新代码之前清除之前的代码。它应该可以正常工作。

附言等效地我认为你也可以在开始新的之前取消上一个超时。参见$timeout.cancel 方法

var i = 0,
ready, scenesCount, activeScene, duration, transition = null;
_init();

// Later on down...

function _init() {
ready = false;

AlexaTourApi.getTour(null).then(function(res) {
$log.log('AlexaTourController got tour', res);
$scope.tour = res;
scenesCount = $scope.tour.scenes.length;
activeScene = 0;

duration = (getActiveScene().hotspots.length + 1) * 2500;
ready = true;
clearTimeoutAndStartNewOne();
});
}
// here we clear the timeout and then we start a new one which is connected to the other function
function clearTimeoutAndStartNewOne() {
if (transition !== null) {
$timeout.cancel(transition);
}
duration = (getActiveScene().hotspots.length + 1) * 2500;
transition = $timeout(_doTransition, duration);
}
// here we simply implement the logic of the timeout to be repeated
function _doTransition() {
activeScene = (i++ % scenesCount);
}

关于javascript - 动态改变 Angular 的 $interval 延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45718709/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com