Fetching api response slow and not be stable

I need to get the value ( totaluser ) as soon as possible , but when the server change the data ( totaluser ) , the reponse is not stable about the time returning , sometimes get the reponse for 30ms and sometimes get for 5000ms , can someone give any solution to get this more stable and get better about the performance ? , i just want to get the value as soon as possible when the server update it? i am not coding the backend .

var refreshIntervalId =  setInterval(function () {
        fetch('**the link for api **')
            .then(res => res.json()).then((out) => {

            var variable = out.totalUser[0].count;

        if( variable > 20 ){
           // do something ...
        }
    })  
    }, 10);

I am trying to understand what you are trying to accomplish. Are you trying to get the total number of users based on a the result of a request to the server or are you wanting to get the total number of users sent to the client if the number of users changes at any given time?

If the first is the desired outcome, then you are currently making a call every 10 ms and the updated data will come in when it wants (you can’t force that). If you are updating the DOM based on the results received, sometimes the changes may be out of sync due to when you finally get it. Plus, polling every 10 ms is overkill. You would be better off using a websocket that “listens” for changes on the server and sends them to the client. It creates a two-way communication to keep the two in sync. The client only gets updated when the total number of users changes on the server (however that is determined on the server).

Hi thank for your helping , i just want to get the totalUser as soon as possible when the server change the data so i fetched 10ms, but i am not coding the backend so i can use websocket ? Could you give me some code to refer about that ?