gpt4 book ai didi

Javascript开始倒计时并在结束时调用ajax

转载 作者:行者123 更新时间:2023-11-28 17:33:20 24 4
gpt4 key购买 nike

我正在尝试使用以下 Javascript 代码启动 Javascript 倒计时。这里是从5 - 0开始计数。

现在我希望当它为0时,我将调用Ajax请求(我知道该怎么做)。但现在,我设置了您的 session 结束的警报消息。

它不断地向我显示警报消息,但应该是一次!

这是 JS 代码:

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;
} else if( timer == 0 ) {
alert('Your time has been completed.');
}
}, 1000);
}

window.onload = function () {
var seconds = 5,
display = document.querySelector('#time');
startTimer(seconds, display);
};

最佳答案

您需要将间隔分配给一个变量,以便您可以在最终警报之后清除该间隔,使其不再运行:

function startTimer(duration, display) {
let timer = duration;
const interval = setInterval(function() {
let minutes = parseInt(timer / 60, 10)
let 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;
} else if (timer == 0) {
alert('Your time has been completed.');
clearInterval(interval);
}
}, 1000);
}

window.onload = function() {
var seconds = 5,
display = document.querySelector('#time');
startTimer(seconds, display);
};
<div id="time"></div>

关于Javascript开始倒计时并在结束时调用ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49788185/

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