简体   繁体   中英

How can I make this clock working without refreshing website?

I have problem with this clock. At first timer didn't show up so I used defer and it appeared but time is only changing when I refresh website.

I just want to make this timer change itself with the real world time not only when I refresh website.

 const hourEl = document.getElementById('hour') const minEl = document.getElementById('minutes') const secEl = document.getElementById('seconds') const ampmEl = document.getElementById('ampm') function clockUpdate() { let h = new Date().getHours() let m = new Date().getMinutes() let s = new Date().getSeconds() let ampm = 'AM' if (h > 12) { h = h - 12; ampm = 'PM'; } hourEl.innerHTML = h; minEl.innerHTML = m; secEl.innerHTML = s; } clockUpdate();
 <span id="hour"></span>:<span id="minutes"></span>:<span id="seconds">:/span> <span id="ampm"></span>

You can use setTimeout(functionRef, delay) for repeat a function after a number of milliseconds and put your function each seconds.

Put your code inside setInterval

 const hourEl = document.getElementById('hour') const minEl = document.getElementById('minutes') const secEl = document.getElementById('seconds') const ampmEl = document.getElementById('ampm') function clockUpdate() { let h = new Date().getHours() let m = new Date().getMinutes() let s = new Date().getSeconds() let ampm = 'AM' if (h > 12) { h = h - 12; ampm = 'PM'; } hourEl.innerHTML = h; minEl.innerHTML = m; secEl.innerHTML = s; } const int = setInterval(clockUpdate, 1000);
 <span id="hour"></span> <span id="minutes"></span> <span id="seconds"></span> <span id="ampm"></span>

Just wrap in a setInterval - here I use half a sec since setInterval is not super reliable

I also use textContent and pad the numbers. You forgot the ampm too

 const hourEl = document.getElementById('hour') const minEl = document.getElementById('minutes') const secEl = document.getElementById('seconds') const ampmEl = document.getElementById('ampm') function clockUpdate() { let h = new Date().getHours() let m = new Date().getMinutes() let s = new Date().getSeconds() let ampm = 'AM' if (h > 12) { h = h - 12; ampm = 'PM'; } hourEl.textContent = String(h).padStart(2,"0"); minEl.textContent = String(m).padStart(2,"0"); secEl.textContent = String(s).padStart(2,"0"); ampmEl.textContent= ampm; } setInterval(clockUpdate,500);
 <span id="hour"></span>:<span id="minutes"></span>:<span id="seconds"></span>:<span id="ampm"></span>

You call the clockUpdate() function only once. Consider moving it into a setInterval()-function that runs every second (or faster for better accuracy)... like so:

setInterval(clockUpdate, 1000);

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