【问题标题】:InnerText flickering after setTimeout设置超时后InnerText闪烁
【发布时间】:2021-04-01 05:05:06
【问题描述】:

我正在处理学校项目之间的一个小项目,我遇到了 DOM 元素的问题,我使用 innerText 从时钟转到文本,然后在 5s 之后,我想清空该文本。一切正常,但文本在一段时间后闪烁。

// Break Time // Break Time // Break Time // Break Time
let inputTime = document.getElementById('breakTimeInput');

document.querySelector('#cta-paus').addEventListener('click', function () {
  if (inputTime.value === '') {
    swal('Break Time', 'You forgot to set break time!', 'warning');
    return;
  }

  let breakTime = inputTime.value * 60;

  setInterval(updateCountdown, 1000);

  function updateCountdown() {
    let minutes = Math.floor(breakTime / 60);
    let seconds = breakTime % 60;

    // Adds zero infront of secunds
    seconds = seconds < 10 ? '0' + seconds : seconds;

    // Out puts the time
    document.querySelector(
      '#MyClockDisplayDown'
    ).innerText = `${minutes}:${seconds}`;
    breakTime--;

    // Removes zero when minutes are done
    if (minutes == 0) {
      document.querySelector('#MyClockDisplayDown').innerText = `${seconds}`;
    }

    // If the count down is finished, write some text
    if (breakTime < 0) {
      document.querySelector('#MyClockDisplayDown').innerText = 'On Air';
      inputTime.value = '';

      setTimeout(() => {
        document.querySelector('#MyClockDisplayDown').innerText = '';
      }, 2000);
    }
  }
});

【问题讨论】:

  • 您的 sn-p 没有运行。您应该添加运行它所需的 HTML。

标签: javascript settimeout innertext


【解决方案1】:

您需要在完成后调用clearIntervalupdateCountdown 函数仍然每秒调用一次

这样的?

...

document.querySelector('#cta-paus').addEventListener('click', function () {
  ...

  var intervalId = setInterval(updateCountdown, 1000);

  function updateCountdown() {
    ...

    // If the count down is finished, write some text
    if (breakTime < 0) {
      ...

      clearInterval(intervalId); // <=== Add this

      setTimeout(() => {
        document.querySelector('#MyClockDisplayDown').innerText = '';
      }, 2000);
    }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-30
    • 2019-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    相关资源
    最近更新 更多