Stay showing the date and time in the browser with javascript

7

Hello.

I want to display the date and time on the page. For this, I started by doing the little 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 have not dealt with the time yet, as I want to show it decreasing, after I solve this detail, I work with the parseInt and ParseFloat () function.

    
asked by anonymous 18.08.2015 / 14:31

5 answers

7

It turns out that in this case the function session() is called only once in the last line of code session(tempo); and then at no time you call the function pegaSession() which is the one that starts in 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 pegaSession() so it starts setInterval

  

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

And clearing the range as suggested by our friend @TobyMosque;)

    
18.08.2015 / 14:50
2

André Birth, if all you want is to display the Date and Time in the Browser, I advise you to ignore this counter and pick up the System Time, as I believe you want to show when the User Session expires, I'll give you an example where 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, simply add more time to the variable dataValidad.

    
18.08.2015 / 15:14
1

If you want to display the current time yourself, use the Date () object of javascript.

Note

As the months are returned in numbers and the day of the week too, 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. p>

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>
    
18.08.2015 / 19:08
1

If you just want a clock, you just have to do one of those things:

<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 timer, you can do it in two ways:

In pure javascript: link
Or at AngularJS: link

    
18.08.2015 / 14:57
0
function DataHora() {  
        var data = new Date();  
        tempo.innerHTML = data;  
        var dataBr = tempo.toLocaleString();  
        setTimeout("DataHora()", 1000);  
    }  

<body onload="DataHora()">  

<span id=tempo></span>  
    
04.12.2015 / 13:15