JS中的防抖函数在websocket的实际应用
项目需求:前端通过websocket接收后端发送的信息,因为后端发送推送消息的频率有时很快,前端频需要频繁请求接口,这样对前端性能有一定的影响,于是就使用到防抖函数,在一定时间内只触发一次请求,节省网络请求
websocket相关代码:
websocket() {
var that=this
let websocket = null;
//判断当前浏览器是否支持WebSocket
if ("WebSocket" in window) {
websocket = new WebSocket("/test");
} else {
console.log("Not support websocket");
}
//连接发生错误的回调方法
websocket.onerror = function (event) {
console.log("web socket onerror");
console.log(event);
};
websocket.onopen = () => {
console.log('Web Socket 已连接上')
// Web Socket 已连接上,使用 send() 方法发送数据
};
//防抖函数debounce使用 1s内只会执行1次
websocket.onmessage = that.debounce(function(){
// that.fetchData();//实际业务接收到信息时调用
console.log('调用了一次');
},1000)
websocket.onclose = () => {
console.log('Web Socket 已关闭')
// Web Socket 已连接上,使用 send() 方法发送数据
};
// 根据实际业务关闭websocket
// this.$router.afterEach(function () {
// websocket.close();
// });
},
防抖函数:
debounce(fn, delay = 1000) { //默认1000毫秒
var timer;
return function() {
var args = arguments;
if(timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, args); // this 指向vue
}, delay);
};
},

浙公网安备 33010602011771号