javascriptonchange continues to flicker when the window is closed

That is because you never clear your intervals. Whenever the user changes the dropdown value, you create a new interval, but the previous ones keep running.

A solution would be to have an interval that is always running, and within you could have the logic for selecting the correct timezone.

Here is an example :

let clock = document.getElementById("clock");
let zoneTitle = document.getElementById("zoneTitle");



function calcTime(city, offset) {
  let d = new Date();

  let utc = d.getTime() + (d.getTimezoneOffset() * 60000);

  let nd = new Date(utc + (3600000 * offset));
  let ndString = nd.toLocaleString().substr(10);
  zoneTitle.innerHTML = city;
  clock.innerHTML = ndString;
}

// Let's set up an object that will match a timezone string to the timezone offset
const offsets = {
  "EST": -5,
  "PST": -8,
  "CST": 1,
  "AST": -4,
  "AEST": 10,
}

// Now run the interval that will update the displayed date
setInterval(function() {
    let selectedTimezoneString = document.getElementById("TimeZones").value // Fetch the selected time zone
    calcTime(selectedTimezoneString, offsets[selectedTimezoneString]);
}, 1000);

// No need to create an event for the dropdown value change since we fetch it every second anyway
<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="styles.css">
    <script src="app.js" charset="UTF-8"></script>
    <link href="https://fonts.googleapis.com/css2?family=Asap:[email protected];700&family=Space+Grotesk:[email protected];500&display=swap" rel="stylesheet">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clock Project</title>
</head>
<body>
    <h1 id="zoneTitle">TimeZone</h1>
    <h1 id="clock">Current Time</h1>

    <select name="time-zones" id="TimeZones">
        <option id="EST" value="EST" selected>EST - Eastern Standard Time</option>
        <option id="PST" value="PST">PST - Pacific Standard Time</option>
        <option value="CST">CST - Central Standard Time</option>
        <option value="AST">AST - Atlantic Standard Time</option>
        <option value="AEST">AEST - Australian Eastern Standard Time</option>
    </select>


</body>
</html>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top