我有3个连续的div显示在页面上,页面加载显示div 1,通过进入第二个它启动一个计时器,当该计时器用完时它返回到第一个div。导航到下一个div应该再次启动计时器。定时器功能在第一页上正常工作,但在第二页上调用它时,它已经从前一个div运行,因此将时间缩短两倍,在最后一个div上记录3次。
如何让它停止当前正在运行的功能然后重新启动呢?
谢谢,
$scope.timeLeft = 0;
var timeoutRunner = function (timerLength) {
$scope.timeLeft = timerLength;
var run = function () {
if ($scope.timeLeft >= 1) {
console.log($scope.timeLeft);
$scope.timeLeft--
$timeout(run, 1000);
} else if ($scope.timeLeft == 0){
$scope.endTransaction();
}
}
run();
}
timeoutRunner(5);
答案 0 :(得分:0)
您需要添加一些调用$timeout.cancel(timeoutRunner);
的逻辑。
答案 1 :(得分:0)
不确定您要在何处准确取消超时(查看更改?当您结束交易时?)但是您可以这样做:
$scope.timeLeft = 0;
var timeoutPromise = false;
var timeoutRunner = function (timerLength) {
$scope.timeLeft = timerLength;
var run = function () {
if ($scope.timeLeft >= 1) {
console.log($scope.timeLeft);
$scope.timeLeft--
timeoutPromise = $timeout(run, 1000);
} else if ($scope.timeLeft == 0){
$scope.endTransaction();
$timeout.cancel(timeoutPromise);
}
}
run();
}
timeoutRunner(5);
答案 2 :(得分:0)
每次调用该函数时,它都会创建一个新的实例,而我无法按需停止它,所以我找到了一种方法来说明我想要运行的实例:
$scope.timeLeft = 0;
var instanceRunning = 0;
var timeoutRunner = function (timerLength, instance) {
$scope.timeLeft = timerLength;
instanceRunning = instance;
var run = function () {
if (instanceRunning == instance){
if ($scope.timeLeft < 7 && $scope.timeLeft > 0){
$('#timer-container').show();
} else {
$('#timer-container').hide();
}
if ($scope.timeLeft >= 1) {
console.log($scope.timeLeft);
$scope.timeLeft--
$timeout(run, 1000);
} else if ($scope.timeLeft == 0){
$scope.endTransaction();
}
}
}
run();
}
timeoutRunner(20, 1);
timeoutRunner(20, 2);
timeoutRunner(20, 3);