Как создать часы / таймер JQuery

У меня есть простой тест приложение, и я хочу показать хороший таймер / часы в верхней части страницы, которая показывает пользователю, как долго они шли. (Если бы я мог как-то показать им таймер для общего времени викторины, а также второй для этого времени вопроса, это было бы еще круче, но я должен быть в состоянии выяснить, как это сделать сам, когда у меня есть один таймер работает.

мой вопрос:

что хороший, простой способ показать простой таймер / часы используя JQuery? (straight JS также в порядке) я знаю, как проверить время, но как получить увеличивающиеся секунды?

мои собственные поиски продолжают вести меня к плагинам JQuery (я хочу свернуть свой собственный), а также "таймеры событий", которые не то, что я ищу...

10 ответов


Вы ищите setInterval функция, которая запускает функцию every x миллисекундах.

например:

var start = new Date;

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

setInterval, как было предложено SLaks, было именно то, что мне нужно, чтобы сделать мой таймер. (Спасибо, приятель!)

использование setInterval и это большое сообщение в блоге Я закончил создание следующей функции для отображения таймера внутри моего div "box_header". Надеюсь, это поможет кому-то еще с аналогичными требованиями!

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

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

            $("h1").text(h+" : "+m+" : "+s);
             setTimeout(function(){getdate()}, 500);
            }

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

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

Как насчет лучшего из обоих миров? Я объединил ответ с форматом операции.

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

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

// 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);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clock"></div>

Если вы можете использовать jQuery с момента.js (большая библиотека), вот как:

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 второй таймер в половине секунды, и он будет на половину секунды позже реального времени.


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. Вот код, который я использовал. Подключите приведенный выше код между тегами . Имейте в виду, что просто наличие этого javascript не будет много делать, если у вас нет html для отображения часов. Я оставлю вам html-код. Дизайн часов, как вы хотите.


    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>

вот ответ @SLaks, но в чистом JavaScript ES6.

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

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

var timeInterval = 5;
    var blinkTime = 1;
    var open_signal = 'top_left';

    $(document).ready(function () {
        $('#div_top_left .timer').html(timeInterval);
        $('#div_top_right .timer').html(timeInterval);
        $('#div_bottom_right .timer').html(timeInterval * 2);
        $('#div_bottom_left .timer').html(timeInterval * 3);

        $('#div_top_left .green').css('background-color', 'green');
        $('#div_top_right .red').css('background-color', 'red');
        $('#div_bottom_right .red').css('background-color', 'red');
        $('#div_bottom_left .red').css('background-color', 'red');

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

    function manageSignals() {
        var top_left_time = parseInt($('#div_top_left .timer').html()) - 1;
        var top_right_time = parseInt($('#div_top_right .timer').html()) - 1;
        var bottom_left_time = parseInt($('#div_bottom_left .timer').html()) - 1;
        var bottom_right_time = parseInt($('#div_bottom_right .timer').html()) - 1;

        if (top_left_time == -1 && open_signal == 'top_left') open_signal = 'top_right';
        else if (top_right_time == -1 && open_signal == 'top_right') open_signal = 'bottom_right';
        else if (bottom_right_time == -1 && open_signal == 'bottom_right') open_signal = 'bottom_left';
        else if (bottom_left_time == -1 && open_signal == 'bottom_left') open_signal = 'top_left';

        if (top_left_time == -1) {
            if (open_signal == 'top_right') {
                top_left_time = (timeInterval * 3) - 1;
                $('#div_top_left .red').css('background-color', 'red');
                $('#div_top_left .yellow').css('background-color', 'white');
                $('#div_top_left .green').css('background-color', 'white');
            }
            else if (open_signal == 'top_left') {
                top_left_time = timeInterval - 1;
                $('#div_top_left .red').css('background-color', 'white');
                $('#div_top_left .yellow').css('background-color', 'white');
                $('#div_top_left .green').css('background-color', 'green');
            }
        }

        if (top_right_time == -1) {
            if (open_signal == 'bottom_right') {
                top_right_time = (timeInterval * 3) - 1;
                $('#div_top_right .red').css('background-color', 'red');
                $('#div_top_right .yellow').css('background-color', 'white');
                $('#div_top_right .green').css('background-color', 'white');
            }
            else if (open_signal == 'top_right') {
                top_right_time = timeInterval - 1;
                $('#div_top_right .red').css('background-color', 'white');
                $('#div_top_right .yellow').css('background-color', 'white');
                $('#div_top_right .green').css('background-color', 'green');
            }
        }

        if (bottom_right_time == -1) {
            if (open_signal == 'bottom_left') {
                bottom_right_time = (timeInterval * 3) - 1;
                $('#div_bottom_right .red').css('background-color', 'red');
                $('#div_bottom_right .yellow').css('background-color', 'white');
                $('#div_bottom_right .green').css('background-color', 'white');
            }
            else if (open_signal == 'bottom_right') {
                bottom_right_time = timeInterval - 1;
                $('#div_bottom_right .red').css('background-color', 'white');
                $('#div_bottom_right .yellow').css('background-color', 'white');
                $('#div_bottom_right .green').css('background-color', 'green');
            }
        }

        if (bottom_left_time == -1) {
            if (open_signal == 'top_left') {
                bottom_left_time = (timeInterval * 3) - 1;
                $('#div_bottom_left .red').css('background-color', 'red');
                $('#div_bottom_left .yellow').css('background-color', 'white');
                $('#div_bottom_left .green').css('background-color', 'white');
            }
            else if (open_signal == 'bottom_left') {
                bottom_left_time = timeInterval - 1;
                $('#div_bottom_left .red').css('background-color', 'white');
                $('#div_bottom_left .yellow').css('background-color', 'white');
                $('#div_bottom_left .green').css('background-color', 'green');
            }
        }

        if (top_left_time == blinkTime && open_signal == 'top_left') {
            $('#div_top_left .yellow').css('background-color', 'yellow');
            $('#div_top_left .green').css('background-color', 'white');
        }
        if (top_right_time == blinkTime && open_signal == 'top_right') {
            $('#div_top_right .yellow').css('background-color', 'yellow');
            $('#div_top_right .green').css('background-color', 'white');
        }
        if (bottom_left_time == blinkTime && open_signal == 'bottom_left') {
            $('#div_bottom_left .yellow').css('background-color', 'yellow');
            $('#div_bottom_left .green').css('background-color', 'white');
        }
        if (bottom_right_time == blinkTime && open_signal == 'bottom_right') {
            $('#div_bottom_right .yellow').css('background-color', 'yellow');
            $('#div_bottom_right .green').css('background-color', 'white');
        }

        $('#div_top_left .timer').html(top_left_time);
        $('#div_top_right .timer').html(top_right_time);
        $('#div_bottom_left .timer').html(bottom_left_time);
        $('#div_bottom_right .timer').html(bottom_right_time);
    }