如何创建JQuery时钟/计时器

时间:2010-04-09 00:54:06

标签: javascript jquery timer clock

我有一个简单的测验应用程序,我希望在页面顶部显示一个漂亮的计时器/时钟,向用户显示他们需要多长时间。 (如果我能以某种方式向他们展示总测验时间的计时器,也可以为这个问题时间显示第二个计时器,这个计时器甚至会更冷,但是一旦我有一个计时器工作,我应该能够弄清楚自己该如何做。 / p>

我的问题是:

使用JQuery显示简单定时器/时钟的简单方法是什么? (直接JS也行不通)我知道如何检查时间,但是如何增加秒数呢?

我自己的搜索引导我继续使用JQuery插件(我想自己推出)以及“事件计时器”,这些都不是我想要的......

11 个答案:

答案 0 :(得分:94)

您正在寻找setInterval函数,该函数每 x 毫秒运行一个函数。

例如:

var start = new Date;

setInterval(function() {
    $('.Timer').text((new Date - start) / 1000 + " Seconds");
}, 1000);

答案 1 :(得分:39)

SLaks建议的setInterval正是我制作计时器所需要的。 (谢谢你的伴侣!)

使用setInterval和this great blog post我最终创建了以下函数来在我的“box_header”div中显示一个计时器。我希望这可以帮助其他有类似要求的人!

 function get_elapsed_time_string(total_seconds) {
  function pretty_time_string(num) {
    return ( num < 10 ? "0" : "" ) + num;
  }

  var hours = Math.floor(total_seconds / 3600);
  total_seconds = total_seconds % 3600;

  var minutes = Math.floor(total_seconds / 60);
  total_seconds = total_seconds % 60;

  var seconds = Math.floor(total_seconds);

  // Pad the minutes and seconds with leading zeros, if required
  hours = pretty_time_string(hours);
  minutes = pretty_time_string(minutes);
  seconds = pretty_time_string(seconds);

  // Compose the string for display
  var currentTimeString = hours + ":" + minutes + ":" + seconds;

  return currentTimeString;
}

var elapsed_seconds = 0;
setInterval(function() {
  elapsed_seconds = elapsed_seconds + 1;
  $('#box_header').text(get_elapsed_time_string(elapsed_seconds));
}, 1000);

答案 2 :(得分:14)

################## JQuery (use API) #################   
 $(document).ready(function(){
         function getdate(){
                var today = new Date();
            var h = today.getHours();
            var m = today.getMinutes();
            var s = today.getSeconds();
             if(s<10){
                 s = "0"+s;
             }
             if (m < 10) {
                m = "0" + m;
            }
            $("h1").text(h+" : "+m+" : "+s);
             setTimeout(function(){getdate()}, 500);
            }

        $("button").click(getdate);
    });

################## HTML ###################
<button>start clock</button>
<h1></h1>

答案 3 :(得分:9)

这两个世界的优点怎么样?我将答案与OP的格式结合起来。

function pretty_time_string(num) {
    return ( num < 10 ? "0" : "" ) + num;
  }

var start = new Date;    

setInterval(function() {
  var total_seconds = (new Date - start) / 1000;   

  var hours = Math.floor(total_seconds / 3600);
  total_seconds = total_seconds % 3600;

  var minutes = Math.floor(total_seconds / 60);
  total_seconds = total_seconds % 60;

  var seconds = Math.floor(total_seconds);

  hours = pretty_time_string(hours);
  minutes = pretty_time_string(minutes);
  seconds = pretty_time_string(seconds);

  var currentTimeString = hours + ":" + minutes + ":" + seconds;

  $('.timer').text(currentTimeString);
}, 1000);

答案 4 :(得分:3)

24小时制:

setInterval(function(){

        var currentTime = new Date();
        var hours = currentTime.getHours();
        var minutes = currentTime.getMinutes();
        var seconds = currentTime.getSeconds();

        // Add leading zeros
        minutes = (minutes < 10 ? "0" : "") + minutes;
        seconds = (seconds < 10 ? "0" : "") + seconds;
        hours = (hours < 10 ? "0" : "") + hours;

        // Compose the string for display
        var currentTimeString = hours + ":" + minutes + ":" + seconds;
        $(".clock").html(currentTimeString);

},1000);

&#13;
&#13;
// 24 hour clock  
setInterval(function() {

  var currentTime = new Date();
  var hours = currentTime.getHours();
  var minutes = currentTime.getMinutes();
  var seconds = currentTime.getSeconds();

  // Add leading zeros
  hours = (hours < 10 ? "0" : "") + hours;
  minutes = (minutes < 10 ? "0" : "") + minutes;
  seconds = (seconds < 10 ? "0" : "") + seconds;

  // Compose the string for display
  var currentTimeString = hours + ":" + minutes + ":" + seconds;
  $(".clock").html(currentTimeString);

}, 1000);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clock"></div>
&#13;
&#13;
&#13;

答案 5 :(得分:2)

如果你可以在Moment.js(伟大的库)中使用jQuery,那就是这样的:

var crClockInit1 = null;
var crClockInterval = null;
function crInitClock() {
    crClockInit1 = setInterval(function() {
        if (moment().format("SSS") <= 40) {
            clearInterval(crClockInit1);
            crStartClockNow();
        }
    }, 30);
}

function crStartClockNow() {
    crClockInterval = setInterval(function() {
        $('#clock').html(moment().format('D. MMMM YYYY H:mm:ss'));
    }, 1000);
}

使用crInitClock()开始时钟初始化。它以这种方式完成同步秒。如果没有同步,你将在半秒内启动1秒计时器,并且在实时之后会延迟半秒。

答案 6 :(得分:0)

var eventdate = new Date("January 01, 2014 00:00:00");

function toSt(n) {
 s=""
 if(n<10) s+="0"
 return s+n.toString();
}

function countdown() {
 cl=document.clock;
 d=new Date();
 count=Math.floor((eventdate.getTime()-d.getTime())/1000);
 if(count<=0)
   {cl.days.value ="----";
    cl.hours.value="--";
    cl.mins.value="--";
    cl.secs.value="--";
    return;
  }
 cl.secs.value=toSt(count%60);
 count=Math.floor(count/60);
 cl.mins.value=toSt(count%60);
 count=Math.floor(count/60);
 cl.hours.value=toSt(count%24);
 count=Math.floor(count/24);
 cl.days.value=count;    

 setTimeout("countdown()",500);
}

你好,我有一个类似的任务,涉及创建一个Javascript倒计时时钟。这是我使用的代码。将上面的代码插入&lt; script language =“Javascript”&gt;&lt; / script&gt;标签。请记住,如果你没有显示时钟的html,那么只有这个javascript不会做太多。我会留下给你写的HTML。按照您的意愿设计时钟。

答案 7 :(得分:0)

    var timeInterval = 5;
    var blinkTime = 1;
    var open_signal = 'signal1';
    var total_signal = 1;

    $(document).ready(function () {
        for (var i = 1; i <= total_signal; i++) {
            var timer = (i == 1) ? timeInterval : (timeInterval * (i - 1));

            var str_html = '<div id="signal' + i + '">' +
                           '<span class="float_left">Signal ' + i + ' : </span>' +
                           '<div class="red float_left"></div>' +
                           '<div class="yellow float_left"></div>' +
                           '<div class="green float_left"></div>' +
                           '<div class="timer float_left">' + timer + '</div>' +
                           '<div style="clear: both;"></div>' +
                           '</div><div class="div_separate"></div>';

            $('.div_demo').append(str_html);
        }

        $('.div_demo .green').eq(0).css('background-color', 'green');
        $('.div_demo .red').css('background-color', 'red');
        $('.div_demo .red').eq(0).css('background-color', 'white');

        setInterval(function () {
            manageSignals();
        }, 1000);
    });

    function manageSignals() {
        var obj_timer = {};

        var temp_i = parseInt(open_signal.substr(6));
        if ($('#' + open_signal + ' .timer').html() == '0')
            open_signal = (temp_i == total_signal) ? 'signal1' : 'signal' + (temp_i + 1);

        for (var i = 1; i <= total_signal; i++) {
            var next_signal = (i == total_signal) ? 'signal1' : 'signal' + (i + 1);

            obj_timer['signal' + i] = parseInt($('#signal' + i + ' .timer').html()) - 1;

            if (obj_timer['signal' + i] == -1 && open_signal == next_signal && total_signal!=1) {
                obj_timer['signal' + i] = (timeInterval * (total_signal - 1)) - 1;

                $('#signal' + i + ' .red').css('background-color', 'red');
                $('#signal' + i + ' .yellow').css('background-color', 'white');
            }
            else if (obj_timer['signal' + i] == -1 && open_signal == 'signal' + i) {
                obj_timer['signal' + i] = (timeInterval - 1);

                $('#signal' + i + ' .red').css('background-color', 'white');
                $('#signal' + i + ' .yellow').css('background-color', 'white');
                $('#signal' + i + ' .green').css('background-color', 'green');
            }
            else if (obj_timer['signal' + i] == blinkTime && open_signal == 'signal' + i) {
                $('#signal' + i + ' .yellow').css('background-color', 'yellow');
                $('#signal' + i + ' .green').css('background-color', 'white');
            }

            $('#signal' + i + ' .timer').html(obj_timer['signal' + i]);
        }
    }
</script>

答案 8 :(得分:0)

Here's @SLaks answer, but in pure ES6 JavaScript.

var start = new Date,
  $timer = document.querySelector('.Timer');

setInterval(function(timestamp) {
    $timer.innerText = `${timestamp - start) / 1000} Seconds`;
}, 1000);

答案 9 :(得分:0)

只需使用@Uday答案代码并建立hr:mm的反向时钟

只是在玩,所以考虑是否有人会需要这个,所以在评论中分享小提琴(Dnt知道为什么stackover流不允许我在此处粘贴链接)

答案 10 :(得分:-1)

FromStr