首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何修改javascript代码中的倒计时器

如何修改javascript代码中的倒计时器
EN

Stack Overflow用户
提问于 2022-06-23 05:35:16
回答 1查看 51关注 0票数 0

有没有一种方法可以操纵倒计时器,使倒计时的时间更快地改变为零?下面是以下代码:

代码语言:javascript
复制
function CalcTimePercent(i, lastpayment, nextpayment, t, p) {

    var time    = nextpayment - t;
    var hour    = parseInt(time / 3600);
    if ( hour < 1 ) hour = 0;
    time = parseInt(time - hour * 3600);
    if ( hour < 10 ) hour = '0'+hour;
 
    var minutes = parseInt(time / 60);
    if ( minutes < 1 ) minutes = 0;
    time = parseInt(time - minutes * 60);
    if ( minutes < 10 ) minutes = '0'+minutes;
    var seconds = time;
    if ( seconds < 10 ) seconds = '0'+seconds;
 
    timer = hour+':'+minutes+':'+seconds;
    document.getElementById('deptimer'+i).innerHTML = timer;


    
    if(timer == "00:00:00") {
        top.location.href='';
    }

            if(timer == "00:00:0-64") {
        top.location.href='';
    }
    t = t + 1;
    setTimeout("CalcTimePercent("+i+", "+lastpayment+", "+nextpayment+", "+t+", "+p+")",1000);
}
EN

回答 1

Stack Overflow用户

发布于 2022-06-24 02:51:24

我能想到的最简单的方法是使用JavaScript的Date类。您将得到计时器结束的时间,以及当前的时间,并不断检查两者之间的差异。在您的案例中,您将如何做到这一点:

代码语言:javascript
复制
let timer = null;

function runTimer(time) {
    clearInterval(timer);

    timer = setInterval(() => {
        const timer = new Date(time.getTime() - new Date().getTime()); // Get difference between now and the end time

        const timerText = `${timer.getUTCHours()}h ${timer.getMinutes()}m ${timer.getSeconds()}s`; // Generate a stylised version of the text
        // document.getElementById("ELEMENT_ID").textContent = timerText; // Apply the stylised text to the timer element
        console.log(timerText); // Apply the stylised text to the timer element
    }, 1000); // Run this every 1000ms (1 second)
}

runTimer(new Date(Date.now() + 10 * 60000)); // Start timer for 10 minutes in the future

setTimeout(() => { // Wait 5 seconds
    runTimer(new Date(Date.now() + 15 * 60000)); // Update timer for 15 minutes in the future
}, 5000);

这种方法的局限性包括它只支持24小时的时间。任何时候都会回环( 27小时的计时器将显示为"2h 0米0“)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72725007

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档