Excess memory usage with timer in javascript

Asked

Viewed 112 times

0

I want to put a timer on a page, the function works, shows the time progressively, but I realized that the use of "setInterval()" begins to consume a lot of page processing until the point of the browser lock for security.

Why then I want to calculate the difference of the current time and the time that opened the page. There is another way to do?

function tempo(){

 var hora = document.getElementById('hora');

 var data = new Date(); 
 hora.value = data.toLocaleTimeString('pt-BR');


 verificarHorario();
 setInterval(tempo ,1000);
}

function verificarDiferencaHorario(inicialMin, finalMin) {
 var totalMin = Number(finalMin - inicialMin);
 var hora2 = document.getElementById('hora2');

 hora2.value = ((Math.trunc(totalMin / 60).toString() + ":" + (totalMin % 60).toString()));
}

function verificarHorario() {

 var inicial = "11:20"; //teste

 var hora = document.getElementById('hora');
 var final = "12:20"; //teste
 var splInicial = inicial.split(":"), splFinal = final.split(":");

 var inicialMin = (Number(splInicial[0] * 60)) + Number(splInicial[1]);
 var finalMin = (Number(splFinal[0] * 60)) + Number(splFinal[1]);

 verificarDiferencaHorario(inicialMin, finalMin);
}   

1 answer

1

There’s a way to improve this code...

  1. Create references for elements outside functions, so they will only be created once

  2. Use recursive functions with setTimeout instead of using setInterval, can improve (motive), but not necessarily going

  3. Do not create a new instance of Date, just "update" the old

Code:

const hora = document.getElementById('hora');

const hora2 = document.getElementById('hora2');

const data = new Date();

(function tempo() {
  hora.value = data.toLocaleTimeString('pt-BR');

  verificarHorario();

  data.setSeconds(data.getSeconds() + 1)

  setTimeout(tempo, 1000);
})();

function verificarDiferencaHorario(inicialMin, finalMin) {
  var totalMin = Number(finalMin - inicialMin);
  hora2.value = ((Math.trunc(totalMin / 60).toString() + ":" + (totalMin % 60).toString()));
}

function verificarHorario() {
  var inicial = "11:20"; //teste
  var final = "12:20"; //teste

  var splInicial = inicial.split(":"),
      splFinal = final.split(":");

  var inicialMin = (Number(splInicial[0] * 60)) + Number(splInicial[1]);
  var finalMin = (Number(splFinal[0] * 60)) + Number(splFinal[1]);

  verificarDiferencaHorario(inicialMin, finalMin);
}
<input id="hora" readonly>
<input id="hora2" readonly>

  • It did not work, the input does not receive and the variable date does not update. What solved my problem was to remove the setInterval from the function time and put outside the scope of the function. thus: var myVar = setInterval(time, 1000);

Browser other questions tagged

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