Necesito comenzar una hora a partir de una fecha de inicio durante n número de días. Cuando uso la fecha (ahora) dentro de la función de intervalo establecido, funciona, pero si uso la fecha desde el parámetro, el tiempo siempre es 0.
let startDate = new Date().getTime(); startTimer(days,startDate) { let today = new Date().getTime(); let countDown = this.addDays(today,days); let countDown2 = new Date(countDown).getTime(); let x = setInterval(() => { let now = new Date().getTime(); //let distance = countDown2 - startDate; //not working when i use startDate here let distance = countDown2 - now; //working when i use 'now' let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); this.displayDate = hours + "h"; if(distance < 0) { clearInterval(x); this.displayDate = "Expired"; } }) } addDays(date, days) { var result = new Date(date); result.setDate(result.getDate() + days); return result; }cuando uso startDate como 10 del parámetro, el o/p es 10d: 0h: 0m: 0s (tiempo siempre 0)
cuando uso cualquier fecha que no sea ahora dentro de setinterval time en o/p será 0 digamos 10d: 0h: 0m: 0s
elimine el inicio de x en el intervalo, y asegúrese de agregar un tiempo en el que el intervalo se base al final del mismo ...
setInterval(() => // end of interval }, 1000) // 1000ms = 1 secondy la función necesita devolver algo... en este ejemplo, incluí las devoluciones en un archivo console.log() solo para visualizarlo, pero eliminarlo es fácil.
if(distance < 0) { clearInterval(x); return console.log("Expired") } else { return console.log(count_days + "d: " + hours + "h: " + minutes + "m: " + seconds + "s") } después de esos cambios, debería poder llamar a la función startTimer() y debería funcionar bien...
startTimer(10, startDate) /* OUTPUT 9d: 23h: 59m: 58s 9d: 23h: 59m: 57s 9d: 23h: 59m: 56s 9d: 23h: 59m: 55s 9d: 23h: 59m: 54s */