Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare dates in Javascript?

I have the following situation:

I have a certain function that runs a loop and does stuff, and error conditions may make it exit that loop. I want to be able to check whether the loop is still running or not.

For this, i'm doing, for each loop run:

LastTimeIDidTheLoop = new Date();

And in another function, which runs through SetInterval every 30 seconds, I want to do basically this:

if (LastTimeIDidTheLoop is more than 30 seconds ago) {
  alert("oops");
}

How do I do this?

Thanks!

like image 496
Daniel Magliola Avatar asked Sep 20 '26 10:09

Daniel Magliola


2 Answers

JS date objects store milliseconds internally, subtracting them from each other works as expected:

var diffSeconds = (new Date() - LastTimeIDidTheLoop) / 1000; 
if (diffSeconds > 30)
{
  // ...
}
like image 179
Tomalak Avatar answered Sep 22 '26 22:09

Tomalak


what about:

newDate = new Date()
newDate.setSeconds(newDate.getSeconds()-30);
if (newDate > LastTimeIDidTheLoop) {
  alert("oops");
}
like image 21
rob Avatar answered Sep 23 '26 00:09

rob