單純使用setInterval會使頁面卡死萎河,setTimeout自帶清除緩存,組合使用實現(xiàn)輪詢可解決瀏覽器崩潰
window.setInterval(() => {
setTimeout(fun, 0)
}, 30000)
完整代碼
<template>
<div></div>
</template>
<script>
export default {
data() {
return {
num: 0,
timer: null,
};
},
destroyed() {
//離開頁面是銷毀
clearInterval(this.timer);
this.timer = null;
},
created() {
// 實現(xiàn)輪詢
this.timer = window.setInterval(() => {
setTimeout(this.getProjectList(), 0);
}, 3000);
},
methods: {
stop() {
clearInterval(this.timer);
this.timer = null;
},
// 請求是否有新消息
getProjectList() {
console.log("請求" + this.num++ + "次");
if(this.num==8){
this.stop()
}
}
}
};
</script>
<style scoped>
</style>