谷歌提供的计时器脚本不满意

Timer Script Supplied by Google not happy

本文关键字:脚本 不满意 计时器 谷歌      更新时间:2023-09-26

谷歌提供给我们的代码有点小问题,用于某些动态广告创意的计时器。

<!DOCTYPE html>
<html>
<head>
<script>
function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
        display.textContent = minutes + ":" + seconds;
        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}
window.onload = function () {
    // Calculate time left till 1600 ZA (1400 GMT)
    var currTime = new Date();
    var endTime = new Date(currTime.getFullYear(),currTime.getMonth(),currTime.getDay(), 14, 0, 0, 1);
    var timeLeft = (endTime - currTime) / 1000;
    var display = document.querySelector('#time');
    if (timeLeft > 0) {
    startTimer(timeLeft, display);
  }
};
</script>
</head>
<body>
<div>Registration closes in <span id="time">00:00</span> minutes!</div>
</body>
</html>

查看代码的 HTML 仅显示以下行:

注册将在00:00分钟后关闭!

就目前而言,它什么也没做,我相信互联网的集体知识可以帮助解决这个问题:)提前感谢!

尝试以下日期计算(请参阅 https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours):

    var currTime = new Date();
    var endTime = new Date();
    endTime.setHours(14,0,0,0);
    var timeLeft = (endTime.getTime() - currTime.getTime()) / 1000;
    alert(timeLeft);

您正在使用getDay()构造endTime - 这将返回星期几,0 表示星期日。 您需要使用 getDate() ,它将返回月份中的某一天:

var endTime = new Date(currTime.getFullYear(),currTime.getMonth(),currTime.getDate(), 14, 0, 0, 1);

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
        display.textContent = minutes + ":" + seconds;
        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}
window.onload = function () {
    // Calculate time left till 1600 ZA (1400 GMT)
    var currTime = new Date();
    var endTime = new Date(currTime.getFullYear(),currTime.getMonth(),currTime.getDate(), 14, 0, 0, 0);
    
    var timeLeft = (endTime - currTime) / 1000;
    var display = document.querySelector('#time');
    
    if (timeLeft > 0) {
    startTimer(timeLeft, display);
  }
};
<div>Registration closes in <span id="time">00:00</span> minutes!</div>

请注意,这些计算完全取决于客户端计算机上设置的日期/时间 - 如果您有重要内容依赖于此,则应从信任的服务器检索时间。