Search code examples
javascriptresetdeadlines

JavaScript - deadline not resetting


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.


Solution

  • 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."