Vue 轮询接口的实现

项目中我们经常需要实现轮询-每隔几秒请求一次接口刷新数据

一般都会使用setInterval,但要注意单纯使用它会导致页面卡死,所以一定要清除定时器

setInterval不会清除定时器队列,每重复执行1次都会导致定时器叠加,最终卡死你的网页。
但是setTimeout是自带清除定时器的

mounted () {
    
    
    const timer = window.setInterval(() => {
    
    
      setTimeout(function () {
    
    
      // chooseProduct 自己封装的axios请求 
        chooseProduct({
    
    
          'promptKey': 'selectitem',
          'serialNum': '000'
        }).then(res => {
    
    
           //视情况而定
          if (String(res.data.success) === 'true') {
    
    
            // 这里可以写一些中止轮询的条件 比如res.data.success返回true时  
            clearInterval(timer)
          }
        })
      }, 0)
    }, 2000)
    // 清除定时器
    this.$once('hook:beforeDestroy', () => {
    
    
      clearInterval(timer)
    })
  }


封装

// polling-utils.js

/**
     * @descripting 轮询功能
     * @param {
    
    String} type 请求类型
     * @param {
    
    String} url 地址 
     * @param {
    
    Object} data 请求数据 
     * @param {
    
    Number} delay 轮询间隔时间
     */
    export default function polling(type, url, data, delay = 1000) {
    
    
        return new Promise((resolve, reject) =>{
    
    
            ajax[type](url, data).then(res => {
    
    
                if (res.data === 'polling') {
    
      // 这个继续进行轮询的条件,需要根据自己的需要修改
                    setTimeout(() => {
                        resolve(polling(type, url, data, delay));
                    }, delay)
                } else {
    
    
                   resolve(res);
               }
           })
       })
    }

使用

import polling from 'utils/polling-utils';

polling('post', url, data).then(res => {
    
     console.log(res) })

猜你喜欢

转载自blog.csdn.net/weixin_46034375/article/details/109078287