gpt4 book ai didi

javascript - 倒计时器 - 凌乱的 Javascript 函数

转载 作者:行者123 更新时间:2023-12-03 02:43:10 25 4
gpt4 key购买 nike


我有一个带有倒计时器功能的代码,但我有一个无法解决的问题 - 如果我再次单击按钮,就会变得一团糟。
我怎样才能让它从新的时间开始计数/或者如果仍在计数则不进行重复计数?
为什么要这样做?

  function myFunctionTimer() {
var timeoutHandle;
function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
var counter = document.getElementById("time");
var current_minutes = mins-1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if( seconds > 0 ) {
timeoutHandle=setTimeout(tick, 1000);
}
if( seconds == 0 ) {
window.location.reload()
}else {
if(mins > 1){
setTimeout(function () { countdown(mins - 1); }, 1000);}}}tick();}
countdown(1);};
 <button onclick="myFunctionTimer()">Click me</button>

<div class="OfertaWazna" >Counter: <span id="time"></span></div>

最佳答案

您需要使超时变量可访问到您的myFunctionTimer,以便下次调用时可以清除该变量

function myFunctionTimer( ele ) {

//attach the timer to the element
var tickTimer = ele.tickTimer;
if ( tickTimer )
{
clearTimeout( tickTimer );
}
// rest of the code

}

还有

  • 不需要创建两个计时器,一个就足够了。只需检查最终时间值是否为 0 即可。
  • 使用addEventListener代替onclick,侵入性更小,可读性更强。

演示

function myFunctionTimer( ele ) {

//attach the timer to the element
var tickTimer = ele.tickTimer;
if ( tickTimer )
{
clearTimeout( tickTimer );
}

function countdown(minutes) {
var seconds = 60;
var mins = minutes

function tick() {
var counter = ele;
var current_minutes = mins - 1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if (seconds > 0) {
ele.tickTimer = setTimeout(tick, 1000); //set the timer here
}
}
tick();
}
countdown(1);
}

document.querySelector( "button" ).addEventListener( "click", function(){
myFunctionTimer( document.getElementById( "time" ) );
});
<button>Click me</button>
<div class="OfertaWazna">Counter: <span id="time"></span></div>

关于javascript - 倒计时器 - 凌乱的 Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48222968/

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