Javascript 幻灯片放映多个承诺的替代方案
我有一个使用ui路由器创建幻灯片的循环。它工作正常,但我不认为这是正确的做法。有人能提供一个替代方案来宣布这么多承诺吗Javascript 幻灯片放映多个承诺的替代方案,javascript,angularjs,angular-ui-router,Javascript,Angularjs,Angular Ui Router,我有一个使用ui路由器创建幻灯片的循环。它工作正常,但我不认为这是正确的做法。有人能提供一个替代方案来宣布这么多承诺吗 define(['./module'], function (controllers) { controllers.controller('homeController', function($timeout, $state, $scope) { var promise; promise = $timeout(function slide() { $sta
define(['./module'], function (controllers) {
controllers.controller('homeController', function($timeout, $state, $scope) {
var promise;
promise = $timeout(function slide() {
$state.transitionTo('home.construcao');
promise1 = $timeout(function () {
$state.transitionTo('home.saude');
}, 3000);
promise2 = $timeout(function () {
$state.transitionTo('home.business');
}, 5000);
promise3 = $timeout(function () {
$state.transitionTo('home.premium');
}, 7000);
promise4 = $timeout(slide, 9000);
}, 0);
$scope.$on('$locationChangeStart', function(){
$timeout.cancel(promise);
$timeout.cancel(promise1);
$timeout.cancel(promise2);
$timeout.cancel(promise3);
$timeout.cancel(promise4);
console.log(promise);
});
});
});
是的,事实上,您不需要像在示例代码中那样在另一个承诺中嵌套多个承诺 只需为所有承诺重用一个变量。然后,当需要取消时,调用$timeout.cancel将该promise变量作为参数传递:
// slide objects contain state labels plus amount of time each slide will
// appear for
var slides = [
{state: 'home.construcao', time: 3000},
{state: 'home.saude', time: 2000},
{state: 'home.business', time: 2000},
{state: 'home.premium', time: 2000}
];
var index = 0; // initialize index (start with first slide)
var promise; // set var here so it's available in scope for $timeout.cancel later
// assign anonymous function to named var so it can be referenced by $timeout
var slide = function(){
// show slide, accessing state label string from array
$state.transitionTo(slides[index].state);
// call $timeout to recursively call this function, which will show next slide
promise = $timeout(slide, slides[index].time);
// if at the last value in the slide array, reset back to the first for
// next slide to be shown
index = (index < slides.length - 1) ? index + 1 : 0;
};
slide(); // start slideshow
$scope.$on('$locationChangeStart', function(){
// interrupt $timeout when event fires; pause slideshow
$timeout.cancel(promise);
}
你到底在问什么?对不起,我编辑了这个问题。现在是正确的,我想知道是否有一种方法可以只声明一个变量而不是promise1、promise1等。这将在位置/路由更改时取消超时循环!我要试试这个!你能用我理解逻辑的方式来评论这些行吗?提前感谢您的评论。希望他们能帮忙。