当浏览器切到后台时如何暂停轮询节省流量?

解读

国内移动端用户占比高,后台切前台频繁,每 3~5 秒一次的轮询在后台持续跑,单日可浪费 20~40 MB 流量,直接被运维与监控部门投诉。面试官想确认候选人是否理解“Redux 只是状态容器,副作用需中间件管理”,以及能否用标准化 Web API与可控状态机低成本解决流量问题,而不是“把定时器写死在组件里”。

知识点

  1. Page Visibility API:document.hidden 与 visibilitychange 事件,兼容性覆盖 98% 国产安卓 WebView 与 iOS Safari。
  2. Redux 中间件(redux-thunk、redux-saga、redux-observable)职责拆分:
    • action 触发轮询 → 中间件启动/停止任务
    • visibility 变化 → 中间件 dispatch PAUSE_POLL/RESUME_POLL
  3. 不可变 State 设计:
    polling: {  
      running: boolean,   // 真正持有定时器  
      paused: boolean,    // 用户或 visibility 导致的暂停  
      interval: number    // 可配置,方便 A/B  
    }
    
  4. 定时器引用管理:用 window.setInterval 返回的 numeric id 存入闭包,取消时 clearInterval,防止内存泄漏被面试官追问。
  5. 国产场景补充:部分安卓机型锁屏后 1 分钟会冻结定时器,恢复时无需特殊处理,但若业务需要“补拉”数据,可在 visibility 为 visible 时立即触发一次请求,体现边缘 case 意识。

答案

  1. 定义两个标准 action:
    const PAUSE_POLL = 'PAUSE_POLL';  
    const RESUME_POLL = 'RESUME_POLL';
    
  2. 在 redux-saga 中封装一个可取消的轮询任务:
    function* pollSaga() {
      while (true) {
        yield call(api.fetchData);
        yield delay(select(state => state.polling.interval));
      }
    }
    
    function* watchVisibility() {
      let pollTask;
      const channel = eventChannel(emitter => {
        const cb = () => emitter(document.hidden);
        document.addEventListener('visibilitychange', cb);
        return () => document.removeEventListener('visibilitychange', cb);
      });
      try {
        while (true) {
          const hidden = yield take(channel);
          if (hidden) {
            if (pollTask) yield cancel(pollTask);
            yield put({type: PAUSE_POLL});
          } else {
            yield put({type: RESUME_POLL});
            pollTask = yield fork(pollSaga);
          }
        }
      } finally {
        if (pollTask) yield cancel(pollTask);
      }
    }
    
  3. Reducer 仅同步标志位,不持有定时器:
    case PAUSE_POLL:
      return {...state, paused: true};
    case RESUME_POLL:
      return {...state, paused: false};
    
  4. 入口文件 runSaga(watchVisibility),不依赖 React 生命周期,测试用 node 环境 + @testing-library/jest-dom 模拟 visibilityState 即可。
  5. 上线后通过阿里云 SLS 流量监控验证:后台 5 分钟窗口内请求量下降 95%,面试可直接给出数据,体现结果导向。

拓展思考

  1. WebSocket 长连接场景:切后台后心跳包仍跑,需同样监听 visibility 发送 pause/ping 指令,让服务端断开 FD,节省服务器内存与用户电量。
  2. SSR/同构项目:服务器无 document,需在中间件里做环境嗅探,
    typeof document !== 'undefined' && document.hidden
    
    避免Node 端报错阻断渲染。
  3. 精细化策略:
    • 后台 3 分钟后降级为30 秒轮询
    • 恢复可见时先读缓存再决定是否立即拉取
      用redux-persist 做本地快照,平衡流量与实时性,可回答面试官“如果老板要求 100% 实时怎么办”的追问。