JavaScript How to switch between two Intervals in Javascript

Two issues here:

1- In your function change, when you set new intervals, you are not clearing the previous ones, causing the old and new intervals to overlap.

You should clear the current interval before setting the new ones (perhaps you could have one interval variable then?).

2- Your if and else if conditions are the same (count % 2 == 0), so the else block will never execute!

var interval = setInterval(showTime12, 0); //a default format

function change(){
    count++;
    clearInterval(interval); //always clear the prev. interval

    if(count % 2 == 0){
        interval = setInterval(showTime12, 0);
    }
    else {
        setInterval(showTime24, 0);
    }
    console.log(count);
}

Edit: A better approach

As many users pointed out, using a single interval and only changing one little variable, the solution would much be much cleaner. So let's have:

var mode = '12'; //say default format is 12

function change(){
    mode = (mode == '12') ? '24' : '12';
}

function run() {
    action = (mode == '12') ? showTime12() : showTime24();
}

var interval = setInterval(run, 0); //a default format
Answer:1

There is a lot of extra work in the provided code. It's possible to fix the dead branch

if(count % 2 == 0){
    clearInterval(a);
}
else if(count % 2 == 0){ // unreachable!
    clearInterval(b);
}

and use this logic to conditionally set an interval (currently, let a = ... is locally scoped, so after change ends, the previous interval is lost without having been cleared), but an improved design would circumvent the problem entirely.

Instead of using two intervals, a preferred approach would be to continually run one interval and have it perform different kinds of work conditionally.

Additionally, setInterval(fn, 1000) can result in some seconds being skipped since the callbacks may be run more than a second apart. Prefer requestAnimationFrame, which offers better control for constantly-updating functions.

There is a lot of repeated logic in the code. In fact, showTime12 and showTime24 are nearly identical. The helper functions can mostly be inlined without compromising readability.

Here's a working example:

const clock = document.querySelector(".clock");
const changeFormatButton = document.querySelector(".change-format");

let militaryTime = false;
changeFormatButton.addEventListener("click", e => {
  militaryTime = !militaryTime;
});

(function showTime() {
  requestAnimationFrame(showTime);
  const date = new Date();
  let amPm = "";
  let hours = date.getHours();
  
  if (!militaryTime) {
    amPm = hours < 12 ? " AM" : " PM";
    hours = hours % 12 || 12;
  }
  
  clock.innerText = `${hours} : ${date.getMinutes()} : ${date.getSeconds()}`
                    .replace(/\d+/g, m => m.padStart(2, "0")) + amPm;
})();
<div class="clock"></div>
<button class="change-format">change format</button>
Answer:2

Was trying to do an restful update. my model.js module.exports.updateGenre = function (id, genre, callback) { var query = {_id: id}; var update = { name: genre.name } Genre....

Was trying to do an restful update. my model.js module.exports.updateGenre = function (id, genre, callback) { var query = {_id: id}; var update = { name: genre.name } Genre....

I have try to stop refresh page on click on select option but when I stop refresh page then data can not get. here code echo "<form name='frmtopdevotees' method='post' action='topuser_load.php'&...

I have try to stop refresh page on click on select option but when I stop refresh page then data can not get. here code echo "<form name='frmtopdevotees' method='post' action='topuser_load.php'&...

  1. retrieving data with php
  2. retrieving data with url
  3. retrieving data with transact-sql
  4. retrieving data with cursors
  5. retrieving data with dbcontext
  6. retrieving data from firebase
  7. retrieving data from hard drive
  8. retrieving data from broken phone
  9. retrieving data from broken iphone
  10. retrieving data from firebase android
  11. retrieving data from database
  12. retrieving data from icloud
  13. retrieving data from mysql using php
  14. retrieving data from external hard drive
  15. retrieving data from dead phone
  16. retrieving data from dead iphone
  17. retrieving data from old hard drive
  18. retrieving data from firebase kotlin
  19. retrieving data in sql
  20. retrieving data from database using php

This regex matches "so" when it's preceded by a comma and a space: (,\s)(so) I want to do the opposite now. I want to tell the regex: don't match "so" if it's preceded by a comma and a space. I ...

This regex matches "so" when it's preceded by a comma and a space: (,\s)(so) I want to do the opposite now. I want to tell the regex: don't match "so" if it's preceded by a comma and a space. I ...

  1. donald trump
  2. donovan mitchell
  3. donald trump twitter
  4. don toliver
  5. donuts
  6. donald trump age
  7. donatos
  8. donald glover
  9. donald trump net worth
  10. donuts near me
  11. donald trump jr
  12. donepezil
  13. don johnson
  14. donald trump speech today
  15. donna shalala
  16. donna summer
  17. donald cerrone
  18. don julio
  19. donnie darko
  20. don quixote

I tried to do this calculation with Node.js. let x = 841251657 console.log((x*x)-x) I got: 707704349563994000 printed. When I use julia I get 707704350405245649 for the same calculation. And I got ...

I tried to do this calculation with Node.js. let x = 841251657 console.log((x*x)-x) I got: 707704349563994000 printed. When I use julia I get 707704350405245649 for the same calculation. And I got ...