2017-08-29 80 views
1

我工作的一个Web应用程序中使用openHab API,并使用SSE控制一些光,但是当灯就亮了,我收到3消息在同一时间接收消息的多个时间相同的事件服务器发送事件

一个与值100 并且与光的实际值的两个另外的相同的消息(例如45) 的值对应于光

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; 
     } 
    }; 

的亮度的%与问题是,我的进度那显示光线在哪里达到100%,然后下降到它应该和我想要的值为了避免这种情况发生,有没有什么办法可以阻止该消息或只为最后收到的消息更新值?

谢谢。

回答

0

如果我们假设这是服务器端的问题或网络问题,则可以在采取任何措施前增加0.1秒的等待时间来解决此问题。然后,如果三条消息同时到达,则只有第三条消息会触发任何UI更改。粗略地这样(未经测试的代码,并且changeUI()中的changeUI()将一定需要整理出来):

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; 
     } 
    }