Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

160
Vistas
Problem with Javascript localStorage for-loop

I am using localStorage to store incoming message: {"lastTid":22,"Hour":10,"min":31,"Second":34} where the time is increasing in every new incoming object, e.g. next object: {"lastTid":22,"Hour":10,"min":31,"Second":35}.

The new messages are being stored in localStorage correctly as seen here:

enter image description here enter image description here

My Javascript code implements the localStorage.getItem and .setItem correctly to retrieve and get my incoming data message, which will be rendered with .innerHTML to var hst, which hst = document.getElementById("highscores"). all code below

The ElementId "highscores" is assigned to <table> tag in my html and comes out as seen here: enter image description here

#js code snippet#

     var hst = document.getElementById("highscores");

     function onMessageArrived(message) {
        
        var data = JSON.parse(message.payloadString);
        var highScores = [data];

        var array = JSON.parse(localStorage.getItem('highscores') || '[]');
        array.push(highScores);

        localStorage.setItem('highscores', JSON.stringify(array));
        for (var i = 0; i < array.length; i++) {
        hst.innerHTML += "<tr><td>" + array[i][0].Hour + ":"+ array[i][0].min + ":" + array[i][0].Second + "</td><td>" + array[i][0].lastTid + "</td></tr>";
        }
    };

My problem is, because of my For loop, when a new message arrives, my loop goes through and renders the previous message and the new message, while the old message is still in the table(please see the table image above). It is displaying object 0, object 0 & 1, then object 0, 1 & 2 all in the same table. Instead of 0, then 1 after, then 2 ... n.

I wish to display the values in proper order and also keep those values even after the page is reloaded. Desired result:

enter image description here

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Don't append directly hst.innerHTML +=...

try something like this

let html = ''
for (var i = 0; i < array.length; i++) {
        html += "<tr><td>" + array[i][0].Hour + ":"+ array[i][0].min + ":" + array[i][0].Second + "</td><td>" + array[i][0].lastTid + "</td></tr>";
}
hst.innerHTML = html

about 4 years ago · Juan Pablo Isaza Denunciar

0

I think the problem is your always appending the array content at hst.innerHTML each incoming message, so the previous loop content remains. It's also not recommended for performance to manipulate DOM inside loops.

let res = '';
for (var i = 0, l = array.length; i < l; i++) {
  res += '<tr><td>' + array[i][0].Hour + ':' + array[i][0].min + ':' + array[i][0].Second + '</td><td>' + array[i][0].lastTid + '</td></tr>';
}
hst.innerHTML = res; // You overwrite the content instead of appending each time.
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda