gpt4 book ai didi

javascript - 使用 DOM 显示倒计时脚本

转载 作者:行者123 更新时间:2023-11-28 09:57:40 24 4
gpt4 key购买 nike

我对 DOM 以及整个 HTML 和 PHP 内容相当陌生,所以我正在寻找一些有关如何执行此操作的信息。到目前为止我所拥有的是Javascript。现在我想/必须使用 DOM 来显示这个脚本。 (仅供引用:我正在为 Moodle 实现一些东西,并且已经这样做了)

我发现 DOM 可以更改不同节点的值。我发现自己遇到的问题是我发现的所有例子都是这样的。点击一个按钮就会发生一些事情。没关系,但现在我希望我的脚本每秒运行一次,这样我就可以让需要它的人看到时间正在流逝。

我希望我给了你足够的信息,我希望你能帮助我。谢谢你试图帮助我。

var running = false
var endTime = null
var timerID = null
// totalMinutes the amount of minutes is put into
var totalMinutes = 3;

function startTimer() {
// running is being started and the current time is put into the variable
running = true
now = new Date()
now = now.getTime()
// Variable endTime gets the time plus the maximum time
endTime = now + (1000 * 60 * totalMinutes);
showCountDown()
}

function showCountDown() {
// same as startTimer, time is saved in variable now
var now = new Date()
now = now.getTime()
if (endTime - now <= 0) {
// Variable timerID gets clearTimeout -->http://de.selfhtml.org/javascript/objekte/window.htm#clear_timeout
clearTimeout(timerID)
// boolean running set to false
running = false
alert("Ihr Resultat wird nun ausgewertet!")
} else {
// delta is being calculated
var delta = new Date(endTime - now)
var theMin = delta.getMinutes()
var theSec = delta.getSeconds()
var theTime = theMin
// show seconds and minutes
theTime += ((theSec < 10) ? ":0" : ":") + theSec
document.getElementById('CheckResults').innerHTML = " (&Uuml;bung in " + theTime + " Minuten abgelaufen)"
if (running) {
timerID = setTimeout("showCountDown()",900)
}
}
}
</script>

最佳答案

您可能想使用 window.setInterval 作为开始。这是一个简短的例子。创建一个空白的 html 页面,将脚本放入 head 部分,将标记放入 body 部分。我无法使用正确的 html 和 body 标签发布它

<script>
function countDownTimer(msecGranularity, output) {
var secRunningTime, startTime, endTime, onFinish, interval;

function heartBeat() {
var diff = endTime - new Date();
output.innerHTML = diff / 1000;
if (diff < 0) {
window.clearInterval(interval);
onFinish();
};
};

this.start = function (secRunningTime, finishHandler) {
onFinish = finishHandler;
startTime = new Date();
endTime = startTime.setSeconds(startTime.getSeconds() + secRunningTime);
interval = window.setInterval(heartBeat, msecGranularity);
}
};

function startTimer(duration, granularity) {
var output = document.createElement("div");
document.getElementById("timerOutputs").appendChild(output);
var t = new countDownTimer(granularity, output);
t.start(duration, function () { output.innerHTML = 'TIMER FINISHED' });
};
</script>

在 HTML 中放置这些来启动计时器类。

<button onclick="startTimer(60,100)">Start a new 60 seconds timer with 100 msec granularity</button><br />
<button onclick="startTimer(600,1000)">Start a new 600 seconds timer with 1000 msec granularity</button>

<div id="timerOutputs">
</div>

关于javascript - 使用 DOM 显示倒计时脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9757683/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com