小程序Ticker倒计时最佳实践

1,810 阅读2分钟

Hello 小伙伴们,如果觉得本文还不错,记得给个 star , 小伙伴们的 star 是我持续更新的动力!GitHub 地址

一. 什么是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: [], onShow: [], onHide: [], onUnload: []
}

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

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

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

/**
 * 增加对Page生命周期方法的拦截器
 * @param methodName
 * @param handler
 */
export function addInterceptor (methodName, handler) {
    Interceptor[methodName] && Interceptor[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

Github: github.com/songdy/todo…