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

时间:2018-04-26 11:10:07

标签: javascript html

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

HTMLcode

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

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>

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

8 个答案:

答案 0 :(得分:2)

工作代码:

<!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 5, 2018 15:37:25").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>

答案 1 :(得分:2)

简单回答如下, HTML部分,

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

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

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);
    }

答案 2 :(得分:1)

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

var myTimer;
function clock() {
    myTimer = setInterval(myClock, 1000);
    var c = 3600; //Initially set to 1 hour. Set this to whatever you desire


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

clock();

也可以将它放在fiddle中。看它是否有效..

答案 3 :(得分:1)

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

 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();

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

FIDDLE

答案 4 :(得分:1)

你可以试试这个;

    <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>

答案 5 :(得分:1)

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

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

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

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));

你的代码确实遭受了一个缺点:如果出于某种原因,呼叫变得稍微分开,这可能会越来越多地造成延迟。您可能想要使用以下行:

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

答案 6 :(得分:1)

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>

答案 7 :(得分:0)

<!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>