如何在Javascript中切换两个时间间隔

如何在Javascript中切换两个时间间隔,javascript,html,Javascript,Html,我正在做一个数字钟。我做了一个按钮,这个按钮改变了时钟的格式(在上午/下午系统和24小时系统之间)。但问题是当我切换时间间隔时,两个时间间隔同时工作,导致时钟以秒为单位变化 我尝试了很多我不记得的事情:/ const clock = document.querySelector('.clock'); const changeFormatButton = document.querySelector('.button-formatChange'); changeFormatButton.addE

我正在做一个数字钟。我做了一个按钮,这个按钮改变了时钟的格式(在上午/下午系统和24小时系统之间)。但问题是当我切换时间间隔时,两个时间间隔同时工作,导致时钟以秒为单位变化

我尝试了很多我不记得的事情:/

const clock = document.querySelector('.clock');
const changeFormatButton = document.querySelector('.button-formatChange');

changeFormatButton.addEventListener('click', change);

let count = 0;
change();

function showTime24(){

    let date = new Date();
    let hours = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();

    hours = addZeros(hours);
    minutes = addZeros(minutes);
    seconds = addZeros(seconds);

    clock.innerHTML = `${hours} : ${minutes} : ${seconds}`;

}

function showTime12(){

    let date = new Date();
    let hours = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();
    let format = changeAMPM(hours);
    hours = changeFormat(hours);

    hours = addZeros(hours);
    minutes = addZeros(minutes);
    seconds = addZeros(seconds);

    clock.innerHTML = `${hours} : ${minutes} : ${seconds} ${format}`;
}

function changeFormat(time){
    if(time > 12){
        time -= 12;
    }
    if(time === 0){
        time = 12;
    }
    return time;
}

function addZeros(time){
    if(time < 10){
        time = '0' + time;
    }
    return time;
}

function changeAMPM(time){
    if(time < 12){
        format = 'AM';
    }
    if(12 < time < 24){
        format = 'PM';
    }
    return format;
}

function change(){
    count++
    let a = setInterval(showTime12, 0);
    let b = setInterval(showTime24, 0);

    if(count % 2 == 0){
        clearInterval(a);
    }
    else if(count % 2 == 0){
        clearInterval(b);
    }
    console.log(count);
}
const clock=document.querySelector('.clock');
const changeFormatButton=document.querySelector(“.button formatChange”);
changeFormatButton.addEventListener('单击',更改);
让计数=0;
改变();
函数showTime24(){
让日期=新日期();
让hours=date.getHours();
让minutes=date.getMinutes();
设秒数=date.getSeconds();
小时=加零(小时);
分钟=添加零(分钟);
秒=加零(秒);
clock.innerHTML=`${hours}:${minutes}:${seconds}`;
}
函数showTime12(){
让日期=新日期();
让hours=date.getHours();
让minutes=date.getMinutes();
设秒数=date.getSeconds();
let format=changeAMPM(小时);
小时=更改格式(小时);
小时=加零(小时);
分钟=添加零(分钟);
秒=加零(秒);
clock.innerHTML=`${hours}:${minutes}:${seconds}${format}`;
}
函数更改格式(时间){
如果(时间>12){
时间-=12;
}
如果(时间==0){
时间=12;
}
返回时间;
}
函数addZeros(时间){
如果(时间<10){
时间='0'+时间;
}
返回时间;
}
功能更改AMPM(时间){
如果(时间<12){
格式='AM';
}
如果(12<时间<24){
格式='PM';
}
返回格式;
}
函数更改(){
计数++
设a=setInterval(showTime12,0);
设b=setInterval(showTime24,0);
如果(计数%2==0){
间隔时间(a);
}
否则如果(计数%2==0){
间隔时间(b);
}
控制台日志(计数);
}
两个钟同时工作。当我点击按钮时,它会越来越有效

这里有两个问题:

1-在函数
change
中,设置新间隔时,没有清除以前的间隔,导致新旧间隔重叠

在设置新的间隔之前,您应该清除当前间隔(也许您可以有一个间隔变量?)

2-您的
if
else if
条件相同(
计数%2==0
),因此
else
块将永远不会执行

var interval = setInterval(showTime12, 0); //a default format

function change(){
    count++;
    clearInterval(interval); //always clear the prev. interval

    if(count % 2 == 0){
        interval = setInterval(showTime12, 0);
    }
    else {
        setInterval(showTime24, 0);
    }
    console.log(count);
}
编辑:更好的方法

正如许多用户指出的那样,使用单一的时间间隔,只需更改一个小变量,解决方案就会更加简洁。让我们来看看:

var mode = '12'; //say default format is 12

function change(){
    mode = (mode == '12') ? '24' : '12';
}

function run() {
    action = (mode == '12') ? showTime12() : showTime24();
}

var interval = setInterval(run, 0); //a default format
多亏了@ggorlen,我成功了

我刚刚在change function中创建了一个函数,并将其设置为setInterval的参数:)


初学者的好的一面是通过犯错误来学习…

在提供的代码中有很多额外的工作。修理那根枯枝是可能的

if(count % 2 == 0){
    clearInterval(a);
}
else if(count % 2 == 0){ // unreachable!
    clearInterval(b);
}
并使用此逻辑有条件地设置一个间隔(当前,
让a=…
是局部范围的,因此在
更改
结束后,前一个间隔将丢失而未被清除),但改进的设计将完全避免此问题

与使用两个时间间隔不同,首选的方法是连续运行一个时间间隔,并让它有条件地执行不同类型的工作

此外,
setInterval(fn,1000)
可能会导致跳过几秒钟,因为回调可能会间隔一秒钟以上运行。首选,它为不断更新功能提供更好的控制

代码中有很多错误。事实上,
showTime12
showTime24
几乎相同。helper函数大部分可以内联而不影响可读性

下面是一个工作示例:

const clock=document.querySelector(“.clock”);
const changeFormatButton=document.querySelector(“.change format”);
让军事时间=假;
changeFormatButton.addEventListener(“单击”,e=>{
军事时间=!军事时间;
});
(函数showTime(){
requestAnimationFrame(显示时间);
const date=新日期();
设amPm=“”;
让hours=date.getHours();
如果(!军事时间){
amPm=小时数<12?“上午”:“下午”;
小时数=小时数%12 | | 12;
}
clock.innerText=`${hours}:${date.getMinutes()}:${date.getSeconds()}`
.替换(/\d+/g,m=>m.padStart(2,“0”))+amPm;
})();


更改格式
,因为旧计时器仍在运行。它们不会被移除。而且,由于用局部变量编码的方式不能真正删除它们。奇怪的是,你正在创建间隔来取消它……你在
change
中的条件非常奇怪——这两个条件都是相同的,因此
else if
中的底部块将永远不会执行。为什么要跑两次间歇?如果在整个时间内都有一个时间间隔,并在多个行为之间切换该时间间隔所做的事情,那会干净得多。@ggorlen我做到了你说的,我成功了!我是个初学者,我是通过犯错误来学习的:)
if(count % 2 == 0){
    clearInterval(a);
}
else if(count % 2 == 0){ // unreachable!
    clearInterval(b);
}