首页 > 解决方案 > Can't make the content of the timer update every second

问题描述

In this code, I create a div element and append it to 'timer' div. I would like to primarily clear the div element to display seconds value every second. However, I get seconds only ONE time. I don't understand how to fix it. I added a check to get rid of child elements of timer(if they exist which of course will happen when many elements will be created). How to make the content of the timer div update every second?

let timer = document.getElementById('timer');
let time = setInterval(() => {
  while (timer.firstChild) {
    timer.removeChild(timer.firstChild);
  }
  timer.append(document.createElement('div').textContent = `${new Date().getSeconds()}`)
}, 1000);   

标签: javascriptsetinterval

解决方案


您的代码似乎正在运行,请尝试此代码段。

let timer = document.getElementById('timer');

let time = setInterval(() => {
  while (timer.firstChild) {
    timer.removeChild(timer.firstChild);
  }

  timer.append(
    document.createElement('div').textContent = `
        ${new Date().getSeconds()}                
  `)
}, 1000);
<div id="timer"></div>


推荐阅读