【发布时间】:2017-08-20 10:08:12
【问题描述】:
我正在构建一个倒计时计时器,它在两个会话值之间交替,一个主会话
和休息时间。我一直在通过
count_down 函数。我无法解决的问题是在结束时
会话我无法让计时器识别新的current_time 值以倒计时;
计时器继续保持先前的值并改为计入负数
认识新的价值。
我已经确认新值通过console.log(current_time)更新到DOM
并且识别出新的价值时间。这个新时间只是没有被计入计数
计时器。
我尝试通过counting=null 和counting=false 将计时器对象设置为空。一世
尝试了计时器对象的内部reset 函数并尝试设置新计时器,但可能不正确。我认识到这是一个范围问题,因为计时器正在保留
从初始开始的倒计时值。我阅读了这些涉及范围的帖子;
one, two,
three,和
决定这个one
尝试将所有的计时功能保持在一个
单个计时对象。
从计时器显示倒计时并转换到第二个计时的最佳方式是什么 完成间隔?任何帮助将不胜感激。谢谢你。
这是最后的努力:
//Timer object
function Current_Countdown(count_down){
var timerObj;
this.pause = function(){
if (timerObj){
clearInterval(timerObj);
}
return this;
}
this.stop = function(){
if (timerObj){
clearInterval(timerObj);
timerObj = null;
}
return this;
}
this.start = function() {
if (!timerObj){
this.stop();
timerObj = setInterval(count_down, 1000);
} else {
timerObj = setInterval(count_down, 1000);
}
}
this.reset = function(){
this.stop().start();
}
}
function pause_count_down(){
counting.pause();;
}
//calls the actual countdown function
function current_count_down(){
if (!counting){
counting = new Current_Countdown(count_down);
counting.start();
} else {
counting.start();
}
}
//performs the countdown and updates the DOM by sending values to display
function count_down(){
curr_time = document.getElementById("current_time").value;
var min_sec_split = curr_time.match(/:/);
var min_sec_index = curr_time.indexOf(min_sec_split);
var minutes = parseInt(curr_time.substring(min_sec_index, 0));
var seconds = parseInt(curr_time.substring(min_sec_index + 1));
console.log(minutes);
console.log(seconds);
if (seconds == 0 && minutes == 0) {
console.log("in final test");
main_control();
}
if (seconds == 0) {
seconds = 60;
minutes -= 1;
}
seconds -= 1;
if (seconds < 10){
seconds.toString();
seconds = "0" + seconds;
}
if (seconds >= 0) {
display_time(minutes, seconds);
}
};
//function to transition between session interval and break interval and back
function main_control(){
var session = document.getElementById("session_number").value;
var current_time = document.getElementById("current_time").value;
var break_time = document.getElementById("break_time").value;
var session_time = document.getElementById("interval_time").value;
in_break = !in_break;
console.log("in_break value: ", in_break);
counting = false;
if (in_break){
console.log("passed display time");
display_time(break_time, "00");
} else {
document.getElementById("session_number").value = parseInt(session) + 1;
display_time(session_time, '00');
}
current_count_down();
}
function display_time(minutes, seconds){
var min = minutes.toString();
var sec = seconds.toString();
var curr_time = min + ":" + sec;
console.log("current time is ", curr_time);
document.getElementById("current_time").value = curr_time;
}
感谢您的宝贵时间和帮助。
【问题讨论】:
标签: javascript timer scope