Skip to content Skip to sidebar Skip to footer

How To Update The Time Every Second Using "setinterval()" Without The Time Flashing In And Out Every Second?

I'm using a dropdown list that displays different timezones onclick using moment-timezone. For example when you click the dropdown labeled 'est' it will display the time in eastern

Solution 1:

Perhaps this will help. I believe you've overcomplicated this just a bit. I've provided comments in the code for you to review.

Note: I did not use moment.js as it is unecessary for your task.

You need:

  1. a time from a Date object
  2. a timezone reference that will change upon click
  3. an interval that will publish the time (with the changing TZ)
  4. Someplace to put the output

// place to put the outputconst output = document.getElementById('output');
// starting timezonevar tz = 'America/New_York';
// Capture click event on the UL (not the li)document.getElementsByTagName('UL')[0].addEventListener('click', changeTZ);

functionchangeTZ(e) {
  // e.target is the LI that was clicked upon
  tz = e.target.innerText;
  // toggle highlighted selection this.querySelectorAll('li').forEach(el=>el.classList.remove('selected'));
  e.target.classList.add('selected');
}

// set the output to the time based upon the changing TZ// Since this is an entire datetime, remove the date with split()[1] and trim itsetInterval(() => {
  output.textContent = newDate(Date.now()).toLocaleString('en-US', {timeZone: `${tz}`}).split(',')[1].trim();
}, 1000);
.selected {
  background-color: lightblue;
}
<div><ul><liclass="selected">America/New_York</li><li>America/Chicago</li><li>America/Los_Angeles</li></ul><divid="output"></div></div>

Solution 2:

Assign your setInterval to a variable and clear it when a user selects the new value form dropdown and restart the interval with new value

var interval = setInterval(updateTime, 1000);
if(oldValue !== newValue){
  clearInterval(interval)
}

Post a Comment for "How To Update The Time Every Second Using "setinterval()" Without The Time Flashing In And Out Every Second?"