Como criar um relógio / temporizador jQuery
-
25-09-2019 - |
Pergunta
Eu tenho um aplicativo simples de questionário e quero exibir um bom timer / relógio na parte superior da página, que mostra ao usuário quanto tempo eles estão indo. (Se eu pudesse, de alguma forma, mostrar a eles um cronômetro para o tempo total do teste e também um segundo para esse tempo de pergunta, que seria ainda mais legal, mas eu seria capaz de descobrir como fazer a mim mesmo que assim que tiver um cronômetro funcionando.
Minha pergunta é:
Qual é uma maneira agradável e fácil de mostrar um timer / relógio simples usando o jQuery? (JS reto também está ok) Eu sei como verificar o tempo, mas como faço para obter segundos incrementadores?
Minhas próprias pesquisas continuam me levando a plugins jQuery (eu quero rolar o meu) e também "temporizadores de eventos" que não são o que estou procurando ...
Solução
Você está procurando o setInterval
função, que executa uma função a cada x milissegundos.
Por exemplo:
var start = new Date;
setInterval(function() {
$('.Timer').text((new Date - start) / 1000 + " Seconds");
}, 1000);
Outras dicas
O SetInterval, conforme sugerido por Slaks, era exatamente o que eu precisava para fazer meu cronômetro. (Obrigado, cara!)
Usando o setInterval e Esta ótima postagem no blog Acabei criando a seguinte função para exibir um cronômetro dentro do meu div. Espero que isso ajude qualquer outra pessoa com requisitos semelhantes!
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;
}
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>
Que tal o melhor dos dois mundos? Combinei a resposta com o formato do 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);
Um relógio de 24 horas:
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>
Se você pode usar o jQuery com o momento.js (Great Library), é assim:
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);
}
Iniciar a inicialização do relógio com crInitClock()
. É feito dessa maneira para sincronizar segundos. Sem sincronização, você começará 1 segundo temporizador em metade do segundo e ficará meio atrasado após o tempo real.
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);
}
Olá, tenho uma tarefa semelhante que envolvia a criação de um relógio de contagem regressiva JavaScript. Aqui está o código que usei. Conecte o código acima entre as tags <script idioma = "javascript"> < /script>. Lembre -se de que apenas ter esse javascript não fará muito se você não tiver o HTML para exibir o relógio. Vou deixar de escrever o HTML para você. Projete o relógio como desejar.
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>
Aqui está a resposta @slaks, mas no puro ES6 JavaScript.
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);
}