-1

So I´m trying to stop a countdown when day,hour, minute and seconds are all zero. I tried clearing the interval in two different ways, but they both don´t work.

function startInterval (){
    const startDate = new Date ();
    const endDate = new Date ("August 15, 2020 17:55:00");

    let timeDifferenceObj = getTimeDifference(startDate, endDate);
    timerDayEl.textContent = timeDifferenceObj.rDays;
    timerHourEl.textContent = timeDifferenceObj.rHours;
    timerMinEl.textContent = timeDifferenceObj.rMinutes;
    timerSecEl.textContent = timeDifferenceObj.rSeconds;
}

let timer = setInterval(startInterval, 1000);

function stopInterval () {
//if (timeDifferenceObj.rDays === 0 & timeDifferenceObj.rHours === 0 & timeDifferenceObj.rMinutes === 0 & timeDifferenceObj.rSeconds === 0 ){
if (startDate === endDate){        
clearInterval(timer);
    }
}

stopInterval();
let timer = setInterval(function() {
    const startDate = new Date ();
    const endDate = new Date ("August 15, 2020 17:50:00");

    let timeDifferenceObj = getTimeDifference(startDate, endDate);
    timerDayEl.textContent = timeDifferenceObj.rDays;
    timerHourEl.textContent = timeDifferenceObj.rHours;
    timerMinEl.textContent = timeDifferenceObj.rMinutes;
    timerSecEl.textContent = timeDifferenceObj.rSeconds;
    if (timeDifferenceObj.rDays === 0 & timeDifferenceObj.rHours === 0 & timeDifferenceObj.rMinutes === 0 & timeDifferenceObj.rSeconds === 0 ){
        clearInterval(timer);
    }
}, 1000)

Thanks for helping

thomalex
  • 59
  • 1
  • 2
  • 8

2 Answers2

0

set your endDate as you wish.

let endDate = new Date ("August 15, 2020 17:55:00");
function startInterval (){

  if((new Date ()).getTime() >=  endDate.getTime())
    {
      clearInterval(timer);
    }
}
    


let timer = setInterval(startInterval, 1000);
sazzad
  • 505
  • 4
  • 5
0

the issue with your code is that you are comparing two date objects with "==" operator, which will not work.


Solution:

use getTime() method : The getTime() method returns the number of milliseconds* since the Unix Epoch. so getTime() method will return a number which can be compared with other numbers with "==" or ">" operator. as I am using set-interval of 1000 millisecond, so "==" may not work, but ">=" will definitely work, so ">=" will be the best approach


code :

var date2 = new Date ("August 15, 2020 17:55:00");

function startInterval (){
  if((new Date ()).getTime() >=  date2.getTime()){
      console.log('-- clear interval going to invoke --')
      clearInterval(timer);
    }
}
    


var timer = setInterval(startInterval, 1000);
subhadip pahari
  • 799
  • 1
  • 7
  • 16