Reputation: 1696
I need start countdown after get time from database.
For example: You've booked a hotel reservation, and after 20 minutes you pay for it.
Where is my problem?
Database:
updated_at = 2016-10-11 11:47:58
HTML(framework is laravel 5):
<input type="hidden" id="updated_at" value="{{ $reserve -> updated_at }}">
<div>Reservation closes in <span id="time"></span> minutes!</div>
script:
function startTimer(duration, display) {
var updated_at = $('#updated_at').val();
console.log(updated_at);
var start = Date.now(updated_at),
diff,
minutes,
seconds;
function timer() {
diff = duration - (((Date.now(updated_at) - start) / 1000) | 0);
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
start = Date.now(updated_at) + 1000;
}
};
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 20,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
Upvotes: 0
Views: 1412
Reputation: 61983
It's fine, except your code to display it is wrong. "display" is not defined in the timer
function, only in the onload
function, and it's not global so that context doesn't carry across. You probably had an error in your browser console, although you didn't mention it. To solve:
1) Change
var fiveMinutes = 60 * 20,
display = document.querySelector('#time');
to simply
var fiveMinutes = 60 * 20;
2) Change
display.textContent = minutes + ":" + seconds;
to
$("#time").text(minutes + ":" + seconds);
3) Change
startTimer(fiveMinutes, display);
to
startTimer(fiveMinutes);
4) Change
function startTimer(duration, display) {
to
function startTimer(duration) {
And that's all.
Upvotes: 1