单击开始按钮时,JavaScript 倒数计时器的小时、分钟和秒数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50041474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:53:00  来源:igfitidea点击:

JavaScript countdown timer for hour, minutes and seconds when a start button click

javascripthtml

提问by Chathuri Fernando

I want to create countdown timer for hour,minute and second when a button click. This is my code so far.

我想在单击按钮时为小时、分钟和秒创建倒数计时器。到目前为止,这是我的代码。

HTMLcode

HTML代码

<div class="colomn" style="margin-right: 20px">
   <button class="start" onclick="clock();">Start</button>
</div>

javascript function

javascript函数

<script>
 var myTimer;
 function clock() {
        myTimer = setInterval(myClock, 1000);
        var c = 5;

        function myClock() {
            document.getElementById("demo").innerHTML = --c;
               if (c == 0) {
                   clearInterval(myTimer);
        }
      }
    }
  </script>

This is simple and not showing separate hour,min and sec. How can I apply this for count hour,min and sec. Please help me.

这很简单,没有显示单独的小时、分钟和秒。我如何将其应用于计数小时、分钟和秒。请帮我。

回答by

Working Code:

工作代码:

<!DOCTYPE HTML>
<html>
<body>

<p id="demo"></p>
<button onclick="countdownTimeStart()">Start Timer</button>

<script>
// Set the date we're counting down to

function countdownTimeStart(){

var countDownDate = new Date("Sep 25, 2025 15:00:00").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

    // Get todays date and time
    var now = new Date().getTime();
    
    // Find the distance between now an the count down date
    var distance = countDownDate - now;
    
    // Time calculations for days, hours, minutes and seconds
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    
    // Output the result in an element with id="demo"
    document.getElementById("demo").innerHTML = hours + "h "
    + minutes + "m " + seconds + "s ";
    
    // If the count down is over, write some text 
    if (distance < 0) {
        clearInterval(x);
        document.getElementById("demo").innerHTML = "EXPIRED";
    }
}, 1000);
}
</script>

</body>
</html>

回答by Romeo Sierra

You need a counter for seconds. During each 1 second interval, decrement this counter, and do the necessary calculations.

你需要一个计数器秒。在每 1 秒间隔内,递减此计数器,并进行必要的计算。

var myTimer;
function clock() {
    myTimer = setInterval(myClock, 1000);
    var c = 3610; //Initially set to 1 hour


    function myClock() {
        --c
        var seconds = c % 60; // Seconds that cannot be written in minutes
        var secondsInMinutes = (c - seconds) / 60; // Gives the seconds that COULD be given in minutes
        var minutes = secondsInMinutes % 60; // Minutes that cannot be written in hours
        var hours = (secondsInMinutes - minutes) / 60;
        // Now in hours, minutes and seconds, you have the time you need.
        console.clear();
        console.log(hours + ":" + minutes + ":" + seconds)
        if (c == 0) {
            clearInterval(myTimer);
        }
    }
}

clock();

Put it in a fiddleas well. See if it works..

也把它放在小提琴上。看看能不能用。。

EDIT: Updated the erroneous code. Thanks to @JDrake for pointing the fact out...

编辑:更新了错误的代码。感谢@JDrake 指出事实...

回答by learn2code

Simple Answer would be as follows, html part,

简单的答案如下,html部分,

<button onclick="clockStart()">Start</button>

<p id="demo"></p>

JS part,

JS部分,

function clockStart() {
          setInterval(function() {
                     date = new Date()
                     let hour = date.getHours();
                     let minutes = date.getMinutes();
                     let seconds = date.getSeconds();
                     document.getElementById("demo").innerHTML = hour + ":"+ minutes + ":" + seconds;
        }, 1000);
    }

回答by Lokesh Ramchandani

var seconds_inputs =  document.getElementsByClassName('deal_left_seconds');
var total_timers = seconds_inputs.length;
for ( var i = 0; i < total_timers; i++){
    var str_seconds = 'seconds_'; var str_seconds_prod_id = 'seconds_prod_id_';
    var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
    var cal_seconds = seconds_inputs[i].getAttribute('value');

    eval('var ' + str_seconds + seconds_prod_id + '= ' + cal_seconds + ';');
    eval('var ' + str_seconds_prod_id + seconds_prod_id + '= ' + seconds_prod_id + ';');
}
function timer() {
    for ( var i = 0; i < total_timers; i++) {
        var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');

        var days = Math.floor(eval('seconds_'+seconds_prod_id) / 24 / 60 / 60);
        var hoursLeft = Math.floor((eval('seconds_'+seconds_prod_id)) - (days * 86400));
        var hours = Math.floor(hoursLeft / 3600);
        var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
        var minutes = Math.floor(minutesLeft / 60);
        var remainingSeconds = eval('seconds_'+seconds_prod_id) % 60;

        function pad(n) {
            return (n < 10 ? "0" + n : n);
        }
        document.getElementById('deal_days_' + seconds_prod_id).innerHTML = pad(days);
        document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = pad(hours);
        document.getElementById('deal_min_' + seconds_prod_id).innerHTML = pad(minutes);
        document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(remainingSeconds);

        if (eval('seconds_'+ seconds_prod_id) == 0) {
            clearInterval(countdownTimer);
            document.getElementById('deal_days_' + seconds_prod_id).innerHTML = document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = document.getElementById('deal_min_' + seconds_prod_id).innerHTML = document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(0);
        } else {
            var value = eval('seconds_'+seconds_prod_id);
            value--;
            eval('seconds_' + seconds_prod_id + '= ' + value + ';');
        }
    }
}

var countdownTimer = setInterval('timer()', 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" class="deal_left_seconds" data-value="1" value="8888888">
                        <div class="box-wrapper">
                            <div class="date box"> <span class="key" id="deal_days_1">00</span> <span class="value">DAYS</span> </div>
                        </div>
                        <div class="box-wrapper">
                            <div class="hour box"> <span class="key" id="deal_hrs_1">00</span> <span class="value">HRS</span> </div>
                        </div>
                        <div class="box-wrapper">
                            <div class="minutes box"> <span class="key" id="deal_min_1">00</span> <span class="value">MINS</span> </div>
                        </div>
                        <div class="box-wrapper hidden-md">
                            <div class="seconds box"> <span class="key" id="deal_sec_1">00</span> <span class="value">SEC</span> </div>
                        </div>

回答by ibrahim tanyalcin

Here is a very primordial clock for you:

这是一个非常原始的时钟给你:

 function clock(t){
    if(clock._stop){return};
    var d = new Date(Date.now());
    console.log(d.getHours()+":"+d.getMinutes()+":"+d.getSeconds()+":"+d.getMilliseconds())
    window.requestAnimationFrame(clock);
}
    clock._stop = false;
    clock();

check your console. To stop the clock do clock._stop = true; To start it, set it back to false and call like clock(). You can wrap the logic inside an other object with getters/setters or whatever you prefer.

检查您的控制台。停止时钟做clock._stop = true;要启动它,请将其设置回 false 并调用 like clock()。您可以使用 getter/setter 或任何您喜欢的方法将逻辑包装在其他对象中。

FIDDLE

小提琴

回答by KOUSIK MANDAL

You can try this;

你可以试试这个;

    <script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <!-- This will start a timer for 5 hours 6 minutes and 7 seconds -->
    <button onclick="countdown(5,6,7)"> Start </button>
    <div><h3 id="timer"></h3></div>
    <script>
    function countdown(hr,mm,ss)
    {
        var interval = setInterval(function(){

            if(hr == 0 && mm == 0 && ss == 0)clearInterval(interval);
            ss--;
            if(ss == 0)
            {
                ss = 59;
                mm--;
                if(mm == 0)
                {
                    mm = 59;
                    hr--;
                }
            }

            if(hr.toString().length < 2) hr = "0"+hr;
            if(mm.toString().length < 2) mm = "0"+mm;
            if(ss.toString().length < 2) ss = "0"+ss;
            $("#timer").html(hr+" : "+mm+" : "+ss);

        },1000)
    }
    </script>

回答by Martijn

You can convert the value in seconds to one in hours, minutes, and seconds:

您可以将以秒为单位的值转换为以小时、分钟和秒为单位的值:

var secs  = Math.floor(c % 60);
var mins  = Math.floor((c/60) % 60);
var hours = Math.floor((c/(60*60)));

This will yield you the amount of seconds left over when removing the minutes (using the modulus operator) and then repeats this for the minutes and hours. You can also easily extend this to include days or weeks:

这将为您提供删除分钟(使用模数运算符)时剩余的秒数,然后对分钟和小时重复此操作。您还可以轻松地将其扩展为包括数天或数周:

var hours = Math.floor((c/(60*60)) % 24);
var days = Math.floor((c/(60*60*24) % 7);
var weeks = Math.floor((c/60*60*24*7));

Your code does suffer from one downside: if for some reason the calls become slightly further apart, this might increasingly build a delay. You might instead want to use the lines:

您的代码确实有一个缺点:如果由于某种原因调用变得稍微远一些,这可能会越来越多地构建延迟。您可能想要使用以下行:

endTime = Date.parse(new Date()) + delay;
timeLeft = endTime - Date.parse(new Date());