javascriptjquerydatetime

How to implement setInterval to update a clock every second?


I'm using the following code to display the current time on my website.

let currentDateTime = new Date();

hours = ('0'+currentDateTime.getHours()).slice(-2);
mins = ('0'+currentDateTime.getMinutes()).slice(-2);

let formattedTime = hours + ":" + mins;

$('#time').html(formattedTime);

This generates the time. However; the time is not running. I was hoping to make this clock run by setting an interval to update the time every second. I've tried adding .setInterval(1000); as follows:

let currentDateTime = new Date();

hours = ('0'+currentDateTime.getHours()).slice(-2);
mins = ('0'+currentDateTime.getMinutes()).slice(-2);

let formattedTime = hours + ":" + mins;

$('#time').html(formattedTime).setInterval(1000);

Unfortunately, this doesn't make the time tick, and leaves me wondering why. I wish to learn what it is that I am doing wrong.


Solution

  • Put all your code in a function and then call it every seconde with setInterval

    function updateTime () {
      let currentDateTime = new Date();
    
      let hours = ('0'+currentDateTime.getHours()).slice(-2);
      let mins = ('0'+currentDateTime.getMinutes()).slice(-2);
      let sec = ('0'+currentDateTime.getSeconds()).slice(-2);
    
      let formattedTime = hours + ":" + mins + ":" + sec;
    
      $('#time').html(formattedTime);
    }
    
    setInterval(updateTime, 1000);
    @import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;500;600&display=swap');
    
    body {
      background:#000;
      padding:10px;
    }
    #time {
      color:#fff;
      font-family: 'Orbitron', sans-serif;
      font-size: 3rem;
      font-weight: 500;
      letter-spacing: .5rem;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="time"></div>