Как сделать так, чтобы время автоматически обновлялось без обновления страницы?

<p id="clock"></p>

subbed = new Date();
hour = subbed.getHours().toString().length < 2 ? '0' + subbed.getHours() : subbed.getHours();
min = subbed.getMinutes().toString().length < 2 ? '0' + subbed.getMinutes() : subbed.getMinutes();
sec = subbed.getSeconds().toString().length < 2 ? '0' + subbed.getSeconds() : subbed.getSeconds();
correct_date = `${hour}:${min}`;
// correct_date = `${hour}:${min}:${sec}`;

let clock = document.getElementById('clock')
setInterval(clock.innerHTML = correct_date, 1000);

Ответы (1 шт):

Автор решения: Vanya228

Можно обернуть в функцию и сделать так:

function clock(){
  let date = new Date(),
         hours = (date.getHours() < 10) ? '0' + date.getHours() : date.getHours(),
         minutes = (date.getMinutes() < 10) ? '0' + date.getMinutes() : date.getMinutes(),
         seconds = (date.getSeconds() < 10) ? '0' + date.getSeconds() : date.getSeconds();
  document.getElementById('clock').innerHTML = hours + ':' + minutes + ':' + seconds;
}
setInterval(clock, 1000);
clock();
→ Ссылка