简体   繁体   中英

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

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 , ie:

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM