小程序列表倒计时最佳实践
发布于 3 年前 作者 jsun 756 次浏览 来自 分享

你的列表倒计时卡顿吗?批量倒计时在运行,性能差吗?如果觉得下文繁琐,建议直接看小程序代码片段: https://developers.weixin.qq.com/s/v6J3SomH7nr2

一. 什么是ticker?

tick本来的意思是钟表的滴答声。Ticker类为游戏开发提供了一个主要的定时类。它主要的目的就是把stage渲染的工作集中起来,也就是说定时调用stage.update()这个方法。Ticker设置的频率也就是游戏的帧数了。
我们把Ticker应用到小程序开发中,频率设置为1s。

Ticker的使用如下,初始化Ticker对象,添加侦听tick事件,启动ticker。

const ticker = new Ticker()
// 参数为Object类型,必须有tick方法
ticker.addTick({
    tick: (delta) => {
    	...
    }
})
ticker.start()

这里不细说Ticker的实现,详情请看Ticker.js源码。

二. 小程序倒计时的烦恼

假如我们都在页面onShow设置setTimeout。
1、onHide取消clearTimeout。假如首页有个倒计时在倒数100S,进入二级页面后,触发onHide,取消clearTimeout。过了10S返回首页,又重新启动setTimeout,那么应该是从100S还是90S开始倒数呢?
那肯定是90S开始呀,可是setTimeout都停了,怎么记录到过去了10S呢?
2、onUnload 取消clearTimeout。onHide之后,其实倒计时还在后台执行,setData也在重新渲染。如果有多级页面,无疑是非常浪费性能。

三. Ticker实现countdown解决方案

在Page的生命周期函数中,添加tick处理。

import ticker from './utils/ticker'

Page({
	countdown: 100,
	// 添加当前页面对象到ticker队列
	onLoad () {
		ticker.addTick(this)
	},
	// 恢复当前页面对象tick
	onShow () {
		ticker.resume(this)
	},
	// 暂停当前页面对象tick
	onHide () {
		ticker.pause(this)
	},
	// 移除当前页面对象tick从ticker队列
	onUnload () {
		ticker.removeTick(this)
	},
	// 需要计时的页面添加tick方法
	tick (delta) {
		countdown -= delta
		this.setData({
			countdown
		})
	}
})

统一处理Page的tick

每个需要用ticker的页面,都需要在各自的生命周期函数里面添加对应的操作。重复的工作交给代码,来重写Page构造函数。interceptor.js

// 生命周期函数集合
const Interceptor = {
  onLoad: [],
  onReady: [],
  onShow: [],
  onHide: [],
  onUnload: []
  // onShareAppMessage: []
}

// 组件生命周期函数集合
const ComponentInterceptor = {
  attached: [],
  show: [],
  hide: [],
  detached: []
}

/**
 * 组合函数,依次执行
 * [@param](/user/param)  {...Function} args 被组合的函数
 */
function compose(interceptorList, sourceMethod, keyName) {
  return function () {
    ;[...interceptorList, sourceMethod].forEach((fn) => {
      typeof fn === 'function' && fn.apply(this, arguments)
    })
  }
}

/**
 * 小程序Page方法的替代实现
 */
const wxPage = Page

/**
 * 重写Page构造函数
 * [@param](/user/param) pageObject - 传入的页面对象
 */
Page = function (pageObject) {
  Object.keys(Interceptor).forEach((keyName) => {
    const sourceMethod = pageObject[keyName]
    pageObject[keyName] = compose(Interceptor[keyName], sourceMethod, keyName)
  })
  return wxPage(pageObject)
}

/**
 * 增加对Page生命周期方法的拦截器
 * [@param](/user/param) methodName
 * [@param](/user/param) handler
 */
export function addInterceptor(methodName, handler) {
  Interceptor[methodName] && Interceptor[methodName].push(handler)
}

/**
 * 小程序Component方法的替代实现
 */
const wxComponent = Component

/**
 * 重写Conponent构造函数
 * [@param](/user/param) componentObject - 传入的页面对象
 */
Component = function (componentObject) {
  componentObject.pageLifetimes = componentObject.pageLifetimes || {}
  Object.keys(ComponentInterceptor).forEach((keyName) => {
    if (['show', 'hide'].includes(keyName)) {
      const sourceMethod = componentObject.pageLifetimes[keyName]
      componentObject.pageLifetimes[keyName] = compose(ComponentInterceptor[keyName], sourceMethod, keyName)
    } else {
      // 兼容Component.lifetimes.attached和Component.attached,detached同理
      let lifetimes = componentObject
      if (componentObject.lifetimes && componentObject.lifetimes[keyName]) {
        lifetimes = componentObject.lifetimes
      }
      const sourceMethod = lifetimes[keyName]
      lifetimes[keyName] = compose(ComponentInterceptor[keyName], sourceMethod)
    }
  })
  return wxComponent(componentObject)
}

/**
 * 增加对Component生命周期方法的拦截器
 * [@param](/user/param) methodName
 * [@param](/user/param) handler
 */
export function addComponentInterceptor(methodName, handler) {
  ComponentInterceptor[methodName] && ComponentInterceptor[methodName].push(handler)
}

小程序入口文件app.js,给页面生命周期函数全局注入ticker对应的方法。

import * as Interceptor from './utils/interceptor'
import ticker from './utils/ticker'

Interceptor.addInterceptor('onLoad', function () {
    ticker.addTick(this)
})

Interceptor.addInterceptor('onShow', function () {
    ticker.resume(this)
})

Interceptor.addInterceptor('onHide', function () {
    ticker.pause(this)
})

Interceptor.addInterceptor('onUnload', function () {
    ticker.removeTick(this)
})

App({
    onLaunch () {
        
    }
})

页面只需要添加tick方法,利用delta计算倒数时间,无需操作ticker逻辑。page.js:

import formatTime from '../../utils/formatTime'
Page({
    countdown: 1000,
    data: {
        countdownStr: ''
    },
    tick (delta) {
        console.log('index tick')
        let countdownStr = formatTime(this.countdown -= delta)
        this.setData({
            countdownStr
        })
    }
});

done

小程序代码片段: https://developers.weixin.qq.com/s/v6J3SomH7nr2

1 回复

滴答滴 滴答滴 滴答滴答滴答滴 大家好才是真的好 广州好迪

回到顶部