0

Update the client side from the server without refreshing the browser window. ex: think there is a variable count=0 and it updates every seconds by setting interval, but it updates in server without reflecting the change in browser.

let count=0

app.get('/', function(req, res){
    setInterval(() => {
        count+=1;
    }, 1000);

  res.json(count); //I need to update UI asynchronously.
}); 
Sanket Naik
  • 78
  • 1
  • 5
  • What do you think this code is doing? There's one request from the browser and one response. So, this code sends one `count` to the client when requested and then the request is finished. You only get to send one response for each request. Meanwhile, each time the client is requested you start another interval timer that runs forever. So, after two requests, you have two interval timers running. – jfriend00 Aug 31 '19 at 05:04
  • 3
    If you want to get a value from the server on a regular interval, then you have two choices. 1) You can make a webSocket connection between client and server and the server can send a new value to the web page over that webSocket connection whenever it wants to. The client then listens for incoming data and responds accordingly when some data arrives. Or, 2) You can send an ajax call from client to server on some sort of client-side timer to fetch the newest value every so often. – jfriend00 Aug 31 '19 at 05:05
  • Thank you @jfriend00, let me check on webSocket. – Sanket Naik Aug 31 '19 at 08:49
  • Thank you once again @jfriend00 webSockets solved my problem :) – Sanket Naik Aug 31 '19 at 11:20

1 Answers1

2

If you want to get a value from the server on a regular interval, then you have a few choices.

  1. You can make a webSocket connection between client and server and the server can send a new value to the web page over that webSocket connection whenever it wants to. The client then listens for incoming data and responds accordingly when some data arrives.

    Socket.io is a library that uses webSocket, but adds a number of useful features such as auto-reconnect, a message wrapper, etc... so that's a choice also.

  2. You can send an ajax call from client to server on some sort of client-side timer to fetch the newest value every so often.

  3. Server-sent events can be used for one-way push of data to the client. While webSocket/socket.io can be used for two-way communication, server-sent events is only for pushing data from server to client. This is a newer technology so you have to make sure your browser base supports it whereas webSockets have been around longer. See WebSockets vs. Server-Sent events/EventSource or Websockets vs. Server-Sent Events for some data comparing server-side events to webSocket.

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979