3

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!

4 Answers 4

7

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

var diffSeconds = (new Date() - LastTimeIDidTheLoop) / 1000; 
if (diffSeconds > 30)
{
  // ...
}
Sign up to request clarification or add additional context in comments.

Comments

5

what about:

newDate = new Date()
newDate.setSeconds(newDate.getSeconds()-30);
if (newDate > LastTimeIDidTheLoop) {
  alert("oops");
}

2 Comments

That just concatenates 30 onto the end, such as "Sun Dec 07 2008 16:45:19 GMT-0500 (EST)30"
Yes, you are right! I have corrected it, with an amended version.
0

You can do like this:

var dateDiff = function(fromdate, todate) {
    var diff = todate - fromdate;
    return Math.floor(diff/1000);
}

then:

if (dateDiff(fromdate, todate) > 30){
    alert("oops");
}

Comments

-1

Create a date object and use setSeconds().

controlDate = new Date();
controlDate.setSeconds(controlDate.getSeconds() + 30);

if (LastTimeIDidTheLoop > controlDate) {
...

1 Comment

This doesn't work, it just sets the time to 30 seconds, like "1:15:30" You want to add 30 seconds, you do controlDate.setSeconds(controlDate.getSeconds() + 30);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.