'Duplicates from websocket

I am receiving a push from a websocket (Java server/servlet) every 5 seconds. This works fine, the json are transmitted and parsed and delivered as planned. However, there are two problems.

  1. I need to clear the between every push or else the result just grows with the same (json) dataset over and over again.

  2. I need to stop the handleMessage()-function duplication data.

This is the javascript code:

    function handleMessage(message) {
        
        document.getElementById('delegate_number').empty();
        document.getElementById('delegate_name').empty();
        document.getElementById('reservation_type').empty();

    var delegates = JSON.parse(message);        
        for (var i=0; i<delegates.length; i++) {
    const nodeDelegateNumber = document.getElementById("delegate_number");
    const nodeDelegateName = document.getElementById("delegate_name");
    const nodeReservationType = document.getElementById("reservation_type");
    
    const cloneDelegateNumber = nodeDelegateNumber.cloneNode(true);
    const cloneDelegateName = nodeDelegateName.cloneNode(true);
    const cloneReservationType = nodeReservationType.cloneNode(true);
    
    document.body.appendChild(cloneDelegateNumber);
    document.body.appendChild(cloneDelegateName);
    document.body.appendChild(cloneReservationType);

    document.getElementById("delegate_number").innerHTML = delegates[i].delegate_number;
    document.getElementById("delegate_name").innerHTML = delegates[i].name_last + ", " + delegates[i].name_first;
    document.getElementById("reservation_type").innerHTML = delegates[i].reservation_type;
    }
}

If my english is bad I apologize. It is not my way of being lazy.

Best regards.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source