0

I am working on a clock in Javascript in which seconds is getting displayed after every 5 seconds which I am not sure why.

The code which I have used for the clock is:

const suv = document.querySelector('#online-suv');
const suvLabel = document.querySelector('#online-suvLabel');

suv.title = suvLabel.title = headingFromDurationstamp(newT, true);


function headingFromDurationstamp(t, inSeconds) {

    let m = new Date(Number(t));
    let sac = ('0' + String(d.getHours())).substr(-2) + ':' + ('0' + String(d.getMinutes())).substr(-2);

    if (inSeconds) {

        sac += ':'  + ('0' + String(d.getSeconds())).substr(-2);
    }
    m = undef;

    return sac;
}


Problem Statement:

I am wondering what changes I need to make in the JS above so that the seconds get displayed every second like a normal clock like this.

flash
  • 1,455
  • 11
  • 61
  • 132

1 Answers1

1

Your logic works perfectly fine. You just have to change few variable misuse like you assigned m to new date and use d out of nowhere to get sac and some d = undef which i'm not sure what for.

Also please check your loop.

setInterval(function() {
  $('.time').html(headingFromDurationstamp(Date.now(), true));
}, 500);

function headingFromDurationstamp(t, inSeconds) {

  let d = new Date(Number(t));
  let sac = ('0' + String(d.getHours())).substr(-2) + ':' + ('0' + String(d.getMinutes())).substr(-2);

  if (inSeconds) {

    sac += ':' + ('0' + String(d.getSeconds())).substr(-2);
  }
  //d = undef;

  return sac;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="time">00:00:00</div>
ACD
  • 1,431
  • 1
  • 8
  • 24
  • I am checking where I have used interval. – flash Dec 05 '18 at 02:45
  • I tried looking but I wasn't able to find it where setInterval function is used. In my website, at the front-end, I am getting the following html. Inside the title attribute clock is present. I am wondering what changes I need to make in your code (in your setInterval function). Your are using .html, I am not sure how I can use attribute there. `
    `
    – flash Dec 05 '18 at 20:15
  • if you're using `title` attribute somehow, you can do: `$('#online-suvLabel').attr('title', headingFromDurationstamp(Date.now(), true));` – ACD Dec 06 '18 at 01:36
  • It did work but the seconds seems to flcker. I am not sure how I can reproduce. – flash Dec 06 '18 at 03:13
  • thats because there's some loop running changing the time. if you really can't find it, change your div id to something else so the other loop can't update it. – ACD Dec 06 '18 at 03:40
  • If we write only this `setInterval(function() { $('#online-suvLabel').attr('title'); }, 500);` whats gonna happen ? – flash Dec 06 '18 at 05:23