🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 前端心跳处理 > ws协议对长时间没有发数据的连接会关闭, 已节省连接资源. ``` var heartCheck = { timeout: 60000,//60ms timeoutObj: null, serverTimeoutObj: null, reset: function(){ clearTimeout(this.timeoutObj); clearTimeout(this.serverTimeoutObj);      this.start(); }, start: function(){ var self = this; this.timeoutObj = setTimeout(function(){ ws.send("HeartBeat"); self.serverTimeoutObj = setTimeout(function(){ ws.close();//如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次 }, self.timeout) }, this.timeout) }, } ws.onopen = function () { heartCheck.start(); }; ws.onmessage = function (event) { heartCheck.reset(); } ws.onclose = function () { reconnect(); }; ws.onerror = function () { reconnect(); }; ``` - 参考资料: [https://www.jianshu.com/p/dfde99d46ef4](https://www.jianshu.com/p/dfde99d46ef4)