A simple method to dynamically display the current time through JS (three steps in place!)

The first step is to determine the DOM element that displays the time

<di class='show-time'>在这里显示动态时间</div>

The second step is to encapsulate the function that obtains the current time and formats the output.

function getCD(){
    
    
    const d = new Date((new Date()).getTime()+8*3600*1000)
    const list = d.toISOString().split(/[^0-9]/).slice(0,-2)
    return `${
      
      list[0]}${
      
      list[1]}${
      
      list[2]}${
      
      list[3]}${
      
      list[4]}${
      
      list[5]}`
}

The third step is to dynamically trigger the function through the timer and display the results to the page.

const printND = setInterval(()=>{
    
    
    document.getElementsByClassName('show-time ')[0].innerHTML = getCD()
},1000)

When you need to stop dynamic display, just call the clear timer method, as follows:

clearInterval(printND)

Guess you like

Origin blog.csdn.net/weixin_43426379/article/details/129973979