如何从数据库获得时间后开始倒计时

How to start countdown after get time from database?

本文关键字:时间 开始 倒计时 数据库      更新时间:2023-09-26

我需要从数据库中获取时间后开始倒计时。

例如

:你预订了旅馆,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) Change

startTimer(fiveMinutes, display);

startTimer(fiveMinutes);

4)变化
function startTimer(duration, display) {

function startTimer(duration) {