Keep displaying the date and time in the javascript browser

Asked

Viewed 1,500 times

7

Hello.

I want to display the date and time on the page. For this, I started doing the small test to display a countdown:

var tempo=60;
function session(time) {
  time=this.tempo;
  if (this.tempo>0) {
    tempo--;
    document.write(tempo);
  }
}
function pegaSession() {
  setInterval(session, 10000);
}
session(tempo);

I haven’t treated the time yet, because I want to show decreasing, after solving this detail, I work with the parseint and parsefloat function().

5 answers

7

It turns out that in this case the function session() is called only once in the last line of the code session(tempo); and then in no time do you call the function pegaSession() which is the one that starts at setInterval

Make the following change

var tempo=60;
var interval;

function session(time) {
time=this.tempo;
if (this.tempo>0) {
    tempo--;
    document.body.innerHTML='';
    document.write(tempo);    
}
else
{
    clearInterval(interval)
}
}

function pegaSession() {
interval = setInterval(session, 1000);
}
pegaSession();

As you can see at the end of the code I call the pegaSession() so it starts setInterval

Note: 10000 milliseconds is equivalent to 10 seconds, if using this setInterval for marking seconds the correct would be 1000 equivalent to 1 second

And cleaning the gap as suggested by our friend @Tobymosque ;)

  • Actually, even calling pegaSession(), does not solve. Gives the error: wyciwyg://36/http://localhost/object/main.php

  • @Andrénascimento execute this code exactly as it is in the answer, and you can see that it is working normally

  • 1

    Silvio, the answer is very good, but I believe that it is interesting to clean this Interval when the time is equal or less than zero, after all it is not legal to leave a function that does nothing running for no reason ;D. https:/jsfiddle.net/uz2qyrg2/

  • @Tobymosque I edited there ;)

2

André Nascimento, if all you want is to show the Date and Time in the Browser, I advise to ignore this counter and take the System Time, as I believe you want to show when the User Session is due to expire, I will put an example where the time runs out in 15 seconds:

var interval = 1000;
var dataValidade = new Date();
var countdown = document.getElementById("countdown");

dataValidade.setSeconds(dataValidade.getSeconds() + 15);
//dataValidade.setHours(dataValidade.getHours() + 1);

var verificarSessao = function () {
  var dataAtual = new Date();
  var tempoRestante = new Date(dataValidade.getTime() - dataAtual.getTime());         
  
  if (tempoRestante.getTime() < 0)
  {
    countdown.textContent = "O seu tempo acabou"
  }
  else
  {    
    tempoRestante.setMinutes(tempoRestante.getMinutes() + tempoRestante.getTimezoneOffset())
    countdown.textContent = "O tempo se esgota em " +  tempoRestante.toTimeString().substring(0, 8) + ".";
    setTimeout(verificarSessao, interval);
  }
}

verificarSessao();
<span id="countdown"></span>

if you want to increase the time, just add more time to the variable dataValidade.

1

If you just want a watch, you just make an exit of that kind:

<body onload="init()">
    <div id="count_label_ms"></div>
        <script>
        var init = function() {
            var interval = setInterval(function() {
            var dataRelogio = new Date();
            var times = [((dataRelogio.getHours() < 10) ? '0': '') +
                           dataRelogio.getHours(),
                         ((dataRelogio.getMinutes() < 10) ? '0': '') +
                           dataRelogio.getMinutes(),
                           dataRelogio.getSeconds()].join(":");

            var strData = [((dataRelogio.getDate() < 10) ? '0': '') + 
                            dataRelogio.getDate() + '/' +
                          ((dataRelogio.getMonth() < 10) ? '0': '') + 
                            dataRelogio.getMonth() + '/' +
                            dataRelogio.getFullYear(), times];
            document.getElementById('count_label_ms').innerHTML = strData.join(' ');
                       });
                   }
        </script> 
</body>

If it’s a countdown, you can do it two ways:

In pure javascript: http://jsfiddle.net/fk2unkb9/31/
Or in Angularjs: http://jsfiddle.net/fk2unkb9/29/

  • copied, pasted in eclipse, but did not display. I read the code superficially, I did not stop to analyze it and study calmly.

  • Don’t get it? What’s the problem?

  • It shows no errors. As I have been given various solutions, I will study them, because I can not talk much without knowing and anything, I comment, even avoids comments my, as layman.

1

If you want to show the current time, use the object Date() javascript.

Observing

As the months are returned in numbers and the day of the week as well, I created an array for the months and one for the days of the week and used the number returned by the object to select the right day and month in the Arrays.

window.onload = setInterval(horario, 1000);

function horario() {
  var relogio = document.querySelector("#relogio");
  var d = new Date();
  var seg = d.getSeconds();
  var min = d.getMinutes();
  var hr = d.getHours();
  var dia = d.getDate();
  var mes = d.getMonth();
  var meses = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"];
  var diaSem = d.getDay();
  var diasSemana = ["Domingo","Segunda-Feira","Terça-Feira","Quarta-Feira","Quinta-Feira","Sexta-Feira","Sábado"];

  relogio.innerHTML = diasSemana[diaSem] + ", " + dia + " de " + meses[mes] + ", " + hr + ":" + min + ":" + seg;
}
<span id="relogio"></span>

  • instead of mounting the string in the hand, because it does not use the Date.prototype.toLocaleString? an example: relogio.innerHTML = new Date().toLocaleString();

  • I didn’t know this method yet, but thank you very much, I tried to help and I ended up learning.

0

function DataHora() {  
        var data = new Date();  
        tempo.innerHTML = data;  
        var dataBr = tempo.toLocaleString();  
        setTimeout("DataHora()", 1000);  
    }  

<body onload="DataHora()">  

<span id=tempo></span>  

Browser other questions tagged

You are not signed in. Login or sign up in order to post.