Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to compare 2 date variables every minute in Javascript?

I’ve 2 date variables in my script, One representing the current time and the other 2 minutes later. My aim is to check both values every minute and trigger a function when current is more or equal than the latter.
Here’s my code and for some reason it doesn’t execute the doing() function

      var current = new Date(Date.now());
  var endtime = new Date(Date.now() + 2 * 60 * 1000);
  hours = ('0' + endtime.getHours()).slice(-2);
  mins = ('0' + endtime.getMinutes()).slice(-2);
  secs = ('0' + endtime.getSeconds()).slice(-2);
  var gametime = hours + ":" + mins + ":" + secs;
  $('#endtime').html(gametime);

  var i = setInterval(function () { myFunction(); }, 60000);

  function myFunction() {
      if (new Date(current) > new Date(endtime)) {
          doing();
      }
  }

  function doing() {
      var body = $('#alert');
      var colors = ['white', 'transparent'];
      var currentIndex = 0;
      setInterval(function () { light(); }, 400);
      function light() {
          body.css({
              backgroundColor: colors[currentIndex]
          });
          if (!colors[currentIndex]) {
              currentIndex = 0;
          } else {
              currentIndex++;
          }
      }
      alert("Time's up!");
      clearInterval(i);
  }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Well, you set current and endtime but neither ever changes, so every time myFunction gets called, the condition evaluates to false and so doing is never called.
I would add an else, that advances current, i.e.:

function myFunction() {
  if (new Date(current) > new Date(endtime)) {
    doing();
  } else {
    current = new Date(Date.now())
  }
}

This way, eventually, current will become greater than endtime.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading