J. Smith
J. Smith

Reputation: 143

Dynamically update a number on a webpage received in node.js?

I'm working with node.js, html, JS and UDP communications.

I have a number (speed of a RC car) being received on my node.js server, and want to display it as a dynamically updating number on my webpage.

Right now I have it showing on the webpage with socket.io but the number only updates if I refresh my page.

node.js function:

function disp_speed(message){
    var speedObj = JSON.parse(message);
    var spd = speedObj.value;
    console.log(spd);
    io.on('connection', function(socket) {
        socket.send(spd);
    });
}

html code:

<p><b>Current Speed:</b> </p>  <p id="speed"></p>

<script>
   var socket = io();
   socket.on('message', function(data){
    document.getElementById("speed").innerHTML = data;
   });
</script>

How can I edit this code to dynamically update the number, rather than only update on refreshing the page?

Upvotes: 0

Views: 979

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138267

io.on('connection', function(socket) {
    socket.send(spd);
});

That means whenever the socket reconnects ( you update the page ) the new data is send to the client. You need to do that to whenever the value gets updated, e.g.:

var speed = 0;

function disp_speed(message){
   var speedObj = JSON.parse(message);
   speed = speedObj.value;
   //propagate update to all sockets
   io.emit("speed", speed);
}

io.on('connection', function(socket) {
    socket.emit("speed", speed);
});

On the client:

socket.on("speed", speed => document.getElementById("speed").textContent = speed);

Upvotes: 3

Related Questions