Receiving message multiple time for same event Server sent event

1.6k views Asked by At

I am working on a Web app to control some light using openHab API and using SSE but when the light goes on I received 3 message at the same time

one with the value 100 and the two other same message with the actual value of the light (ex 45) the value correspond to the % of the brightness of the light

eventSource.onmessage = (event: any) => {
      this.val = JSON.parse(JSON.parse(event.data).payload).value;
      console.log("new val " + this.val);
      slid.value = this.val;
      if(this.val >= 1){
        this.light = true;
        button.checked= true;
      }
      else{
        this.light = false;
        button.checked = false;
      }
    };

the problem with that is that my progressbar that show where the light is goes to 100% then descend to the value it should and I would like to avoid that is there any thing to prevent the message or to update the value only for the last message received ?

thanks.

1

There are 1 answers

6
Darren Cook On BEST ANSWER

If we assume this is a bug on the server-side, or a network problem, you could workaround it by adding a 0.1s wait before taking any action. Then if three messages arrive at the same time, only the 3rd will trigger any UI changes. Roughly like this (untested code, and the this.light in changeUI() will definitely need sorting out):

var timer = null;

eventSource.onmessage = (event: any) => {
      this.val = JSON.parse(JSON.parse(event.data).payload).value;
      console.log("new val " + this.val);
      if(timer)clearTimeout(timer);
      timer = setTimeout(changeUI, 100, this.val);
      };

function changeUI(val){
    if(timer){clearTimeout(timer);timer=null;}   //Redundant but harmless
    slid.value = val;
    if(val >= 1){
        this.light = true;
        button.checked= true;
      }
    else{
        this.light = false;
        button.checked = false;
      }
    }