每隔几秒请求一次接口

轮询 - 每隔几秒请求一次接口实现数据更新

单纯使用setInterval会使页面卡死,setTimeout自带清除缓存,组合使用实现轮询可解决浏览器崩溃.

<template>
    <div>
        <button @click="dataset_log">test</button>
        <ul>
             <li v-for="(item, index) in data" :key="index">{{ item }}</li>
        </ul>
    </div>
</template>

<script>

export default {
    props: ['getData','data'],
    name: 'exe',
    data() {
        return {
            timer: null,
            num: 0,
        }
    },
    destroyed() {
        //离开页面是销毁
        clearInterval(this.timer);
        this.timer = null;
  },
    mounted(){
        this.timer = window.setInterval(() => {
        console.log("timer")
        console.log(this.timer)
        setTimeout(this.dataset_log(), 0);
      }, 3000);
    },
    methods: {
        dataset_log() {          
            this.getData("send request dataset log")
               console.log("请求" + this.num++ + "");
               if(this.num==8){
                   this.stop() 
                }
        },
        stop() {
            clearInterval(this.timer);
            this.timer = null;
            this.num = 0
    },
    },

}
</script>

 相当于自动点击按钮,向后端发起请求。

posted @ 2023-08-10 23:06  半日闲1  阅读(57)  评论(0编辑  收藏  举报