0

Can anybody tell me why the deadline isn't reset once it is reached (i.e. the 'else' section)?

var timeInMinutes = 1;
var currentTime = Date.parse(new Date());

var deadline = localStorage.deadline;
if(deadline) {
    deadline = new Date(deadline);
}else {
    deadline = new Date(Date.now() + timeInMinutes*60*1000);
    localStorage.deadline = deadline;
}

Thanks.

mellows
  • 303
  • 1
  • 7
  • 27
  • You should use `localStorage.getItem()` `localStorage.setItem()` to access localStorage properties. – Robusto May 07 '16 at 21:17
  • @Robusto, using `getItem()` and `setItem()` is recommended but not necessary. – Rick Hitchcock May 07 '16 at 21:25
  • Not sure I understand the question. The first time through, the `else` statement will run because `deadline` is undefined. All subsequent times, `deadline` will be defined, so only the `if` statement will run. Where is the code to "reset" `deadline`? – Rick Hitchcock May 07 '16 at 21:29
  • The `else` statement is supposed to set/reset the deadline and then until that deadline is reached the `if` statement is carried out. Then once the deadline is reached the `else` statement is carried out resetting the deadline. – mellows May 07 '16 at 21:35
  • How should I implement this? – mellows May 07 '16 at 21:46
  • As in what would the code look like for the if condition? – mellows May 07 '16 at 21:47

1 Answers1

1

The else statement will run only the first time, because deadline will always be "truthy" after that.

Since the else statement should run the first time and whenever the deadline has passed, change your if condition to this:

var deadline = localStorage.deadline;
if(deadline && new Date() < new Date(deadline)) {
  deadline = new Date(deadline);
} else {
  deadline = new Date(Date.now() + timeInMinutes*60*1000);
  localStorage.deadline = deadline;
}

That basically says, "If there's a deadline and we haven't hit it, keep using the current deadline. Else, set a new deadline."

Rick Hitchcock
  • 35,202
  • 5
  • 48
  • 79