[英]How to set interval time?
I have use following function for timer 我为计时器使用了以下功能
function startTimer(duration) {
$rootScope.timer = duration;
$rootScope.minute = 0;
$rootScope.second = 0;
$rootScope.Minutes = 0;
$rootScope.Seconds = 0;
setInterval(function () {
$rootScope.minute = parseInt($rootScope.timer / 60, 10)
$rootScope.second = parseInt($rootScope.timer % 60, 10);
$rootScope.Minutes = $rootScope.minute < 10 ? "0" +
$rootScope.minute : $rootScope.minute;
$rootScope.Seconds = $rootScope.second < 10 ? "0" +
$rootScope.second : $rootScope.second;
if (--$rootScope.timer < 0) {
$rootScope.timer = duration;
}
}, 1000);
}
startTimer(300);
I am using $rootScope.Minutes
and $rootScope.Seconds
in view to display time. 我正在使用
$rootScope.Minutes
和$rootScope.Seconds
来显示时间。 And time reduce by seconds . 而且时间减少了几秒钟。 but if i close timer and open again it will reduce by 2 seconds.
但是,如果我关闭计时器然后再次打开,它将减少2秒。 and again i close and open then it will reduce by 3 seconds.
再一次我关闭并打开,它将减少3秒。 like wise iterations goes.
就像明智的迭代一样。 I do not know where i did mistake.
我不知道我在哪里弄错了。 Please help me.
请帮我。
Every time you call startTimer
, it will fire off another setInterval
, which will run independently. 每次调用
startTimer
,它将触发另一个setInterval
,它将独立运行。 Because you are using the same variables, each setInterval
will operate on your $rootScope.timer
variable independently. 因为您使用的是相同的变量,所以每个
setInterval
都将对$rootScope.timer
变量进行独立操作。
The solution is to save a handle to the setInterval
at the start, and clearInterval
before setting a new interval. 解决方案是在开始时将句柄保存到
setInterval
,并在设置新间隔之前将clearInterval
保存。
function startTimer(duration) {
$rootScope.timer = duration;
$rootScope.minute = 0;
$rootScope.second = 0;
$rootScope.Minutes = 0;
$rootScope.Seconds = 0;
// modified bit
if($rootScope.internvalhandle) clearInterval($rootScope.internvalhandle);
$rootScope.internvalhandle = setInterval(function () {
$rootScope.minute = parseInt($rootScope.timer / 60, 10)
$rootScope.second = parseInt($rootScope.timer % 60, 10);
$rootScope.Minutes = $rootScope.minute < 10 ? "0" +
$rootScope.minute : $rootScope.minute;
$rootScope.Seconds = $rootScope.second < 10 ? "0" +
$rootScope.second : $rootScope.second;
if (--$rootScope.timer < 0) {
$rootScope.timer = duration;
}
}, 1000);
}
startTimer(300);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.