javascript 中局部范围变量中的计时器

Timer in a local scope variable in javascript

计时器必须初始化,秒数必须每秒递增。有人能帮我吗?我不确定发生了什么。

function timer(){
    let seconds = "00";
    let minutes = "00";
    let hours = "00";
    let fulltime = `${hours}:${minutes}:${seconds}`;

    const incrementSeconds = () => {
        secondsAsNumber = parseInt(seconds) + 1;
        seconds = secondsAsNumber.toString();
    }
    
    const displayTime = () => {
        console.log(fulltime);
    }
    
    setInterval(() => {
        incrementSeconds();
        displayTime();
    }, 1000);
}

timer();

它记录:

00:00:00
00:00:00
00:00:00
00:00:00
00:00:00
00:00:00
00:00:00

在增加秒数后更新您的 fulltime 变量:

function timer(){
    let seconds = "00";
    let minutes = "00";
    let hours = "00";
    let fulltime = `${hours}:${minutes}:${seconds}`;

    const incrementSeconds = () => {
        secondsAsNumber = parseInt(seconds) + 1;
        seconds = secondsAsNumber.toString();
        // Update fulltime variable
        fulltime = `${hours}:${minutes}:${seconds < 10 ? "0" + seconds : seconds}`;
    }
    
    const displayTime = () => {
        console.log(fulltime);
    }
    
    setInterval(() => {
        incrementSeconds();
        displayTime();
    }, 1000);
}

timer();

那么它应该输出:

00:00:01
00:00:02
00:00:03
00:00:04
00:00:05

... and so on ...

这是你需要的

function timer() {
    let seconds = "0";
    let minutes = "0";
    let hours = "0";
    let fulltime = `${hours}:${minutes}:${seconds}`;

    const incrementSeconds = () => {
      let secondsAsNumber = parseInt(seconds) + 1;
      seconds = secondsAsNumber.toString();

      if (seconds > 59) {
        minutes = parseInt(minutes) + 1;
        seconds = 0;
      }
      if (minutes > 59) {
        hours = parseInt(hours) + 1;
        minutes = 0;
      }
      // Update fulltime variable

      fulltime = `${hours < 10 ? "0" + hours : hours}:${
        minutes < 10 ? "0" + minutes : minutes
      }:${seconds < 10 ? "0" + seconds : seconds}`;
    };

    const displayTime = () => {
      console.log(fulltime);
    };

    setInterval(() => {
      incrementSeconds();
      displayTime();
    }, 1000);
  }

  timer();