// utils/compatibility.ts /** * 兼容 requestAnimationFrame */ export const requestAnimationFrame = (callback: FrameRequestCallback): number => { // 微信小程序环境 // #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-QQ return setTimeout(() => { callback(Date.now()) }, 16) as unknown as number // #endif // H5 环境 // #ifdef H5 return window.requestAnimationFrame(callback) // #endif // App 环境 // #ifdef APP return setTimeout(() => { callback(Date.now()) }, 16) as unknown as number // #endif } /** * 兼容 cancelAnimationFrame */ export const cancelAnimationFrame = (id: number): void => { // 微信小程序环境 // #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-QQ return clearTimeout(id) // #endif // H5 环境 // #ifdef H5 return window.cancelAnimationFrame(id) // #endif // App 环境 // #ifdef APP return clearTimeout(id) // #endif } /** * 安全执行 requestAnimationFrame,避免错误 */ export const safeRequestAnimationFrame = (callback: FrameRequestCallback): number => { try { return requestAnimationFrame(callback) } catch (error) { // 如果 requestAnimationFrame 不存在,使用 setTimeout 模拟 return setTimeout(() => { callback(Date.now()) }, 16) as unknown as number } } /** * 安全执行 cancelAnimationFrame */ export const safeCancelAnimationFrame = (id: number): void => { try { cancelAnimationFrame(id) } catch (error) { clearTimeout(id) } }