我需要从数据库获取时间后开始倒计时。
例如: 您已预订酒店,20 分钟后即可付款。
我的问题出在哪里?
数据库:
updated_at = 2016-10-11 11:47:58
HTML(框架是laravel 5):
<input type="hidden" id="updated_at" value="{{ $reserve -> updated_at }}">
<div>Reservation closes in <span id="time"></span> minutes!</div>
脚本:
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);
};
请您参考如下方法:
没问题,只是你的显示代码是错误的。 “display”没有在timer
函数中定义,仅在onload
函数中定义,并且它不是全局的,因此上下文不会传递。您的浏览器控制台可能出现错误,尽管您没有提及。解决方法:
1)改变
var fiveMinutes = 60 * 20,
display = document.querySelector('#time');
简单
var fiveMinutes = 60 * 20;
2)改变
display.textContent = minutes + ":" + seconds;
至
$("#time").text(minutes + ":" + seconds);
3)更改
startTimer(fiveMinutes, display);
至
startTimer(fiveMinutes);
4)改变
function startTimer(duration, display) {
至
function startTimer(duration) {
仅此而已。