Home > Software engineering >  How to compare 2 date variables every minute in Javascript?
How to compare 2 date variables every minute in Javascript?

Time:08-31

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);
  }

CodePudding user response:

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.

CodePudding user response:

Thanks to Konrad Linkowski who told me to update the variables, I updated "Current" time variable inside the interval which solved the issue.

  • Related