简体   繁体   中英

I have time & date function ,but I want to automatically update it , should I use set Interval Method ? How?

This date and time function is good ,but it does not automatically running, can you show me pls how can I fix it ? Time just show up after reloading page , time is not running

  const initApp = () => {
   let today = new Date()

   let month = today.getMonth() + 1
   let year = today.getFullYear()
   let date = today.getDate()
   let currentdate = `${month}/${date}/${year}`

   let h = addZero(today.getHours())
   let m = addZero(today.getMinutes())
   let s = addZero(today.getSeconds())

   let time = `${h}:${m}:${s}`

   let output = ` ${currentdate}  ${time}`

   const datenow = document.querySelector('.datenow')
   datenow.innerText = output

  }

  function addZero(num) {
    return num < 10 ? `0${num}`:num;
  }

Do I understand right?

 const initApp = () => { let today = new Date() let month = today.getMonth() + 1 let year = today.getFullYear() let date = today.getDate() let currentdate = `${month}/${date}/${year}` let h = addZero(today.getHours()) let m = addZero(today.getMinutes()) let s = addZero(today.getSeconds()) let time = `${h}:${m}:${s}` let output = ` ${currentdate} ${time}` const datenow = document.querySelector('.datenow') datenow.innerText = output } function addZero(num) { return num < 10 ? `0${num}`:num; } setInterval(() => { initApp(); }, 1000);
 <div class="datenow"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM