Implementation of Vue polling interface

In projects, we often need to implement polling-request interface refresh data every few seconds

SetInterval is generally used, but it should be noted that simply using it will cause the page to freeze, so be sure to clear the timer

setInterval will not clear the timer queue. Every time it is executed repeatedly, it will cause the timer to overlap and eventually freeze your web page.
But setTimeout comes with a clear timer

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)
    })
  }


Package

// 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);
               }
           })
       })
    }

use

import polling from 'utils/polling-utils';

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

Guess you like

Origin blog.csdn.net/weixin_46034375/article/details/109078287