@silver-zepp/sequence-bg
Version:
Sequence BG - ZeppOS specific Sequence that works in the background.
2 lines • 2.57 kB
JavaScript
/** @about SysTimer 1.0.0 @min_zeppos 2.0 @author: Silver, Zepp Health. @license: MIT */
import{createSysTimer,stopTimer}from"@zos/timer";function SystemTimer(){this.MAX_TIMERS=10;this.active_timers=0;this.timer_ids=new Set;this.reminder_last_time=Date.now();this.reminder_interval=6e4;this.is_reminder_enabled=false}SystemTimer.prototype={setTimeout(callback,delay,...args){return this.createTimer(false,delay,callback,...args)},setInterval(callback,delay,...args){return this.createTimer(true,delay,callback,...args)},setImmediate(callback,...args){return this.createTimer(false,0,callback,...args)},clear(id){if(this.use_systimer){if(id!==null&&this.timer_ids.has(id)){stopTimer(id);this.active_timers--;this.timer_ids.delete(id)}}else{clearTimeout(id);clearInterval(id)}},stopAllTimers(){for(const id of this.timer_ids){if(this.use_systimer){stopTimer(id)}else{clearTimeout(id);clearInterval(id)}}this.timer_ids.clear();this.active_timers=0},setOptions(options={}){const{use_systimer,reminder,reminder_interval}=options;if(reminder!==undefined){this.is_reminder_enabled=reminder}if(reminder_interval!==undefined){if(reminder_interval>=1e3){this.reminder_interval=reminder_interval}else{this.reminder_interval=1e3}}if(use_systimer!==undefined){this.use_systimer=use_systimer;if(this.use_systimer&&typeof createSysTimer==="undefined"){console.log("System Timer is not available, using JS timer");this.use_systimer=false}}},getStatus(){return{active_timers:this.active_timers,use_systimer:this.use_systimer,reminder:this.is_reminder_enabled,reminder_interval:this.reminder_interval}}};SystemTimer.prototype.checkAndRemind=function(){const now=Date.now();if(this.is_reminder_enabled&&now-this.reminder_last_time>=this.reminder_interval){this.reminder_last_time=now}};SystemTimer.prototype.createTimer=function(is_repeat,delay,callback,...args){if(typeof callback!=="function"){console.log("ERR: Callback must be a function");return null}if(this.use_systimer){if(this.active_timers>=this.MAX_TIMERS){console.log("WARN: Cannot create more than 10 system timers");return null}if(delay>=0&&delay<1e3){delay=1e3}const cb_with_reminder=()=>{this.checkAndRemind();callback(...args);if(!is_repeat){this.active_timers--;this.timer_ids.delete(id)}};const id=createSysTimer(is_repeat,delay,cb_with_reminder);if(id){this.active_timers++;this.timer_ids.add(id)}else{console.log("Failed to create system timer")}return id}else{if(is_repeat){return setInterval(callback,delay,...args)}else{return setTimeout(callback,delay,...args)}}};const SysTimer=new SystemTimer;export{SysTimer};