123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124 |
- ---@alias TimerBaseData {time:number,nextTime:number,count:number,func:function,args:any,isTimerStop:boolean}
- ---@class TimerBase
- local TimerBase = {}
- local this = TimerBase
- ---@class timers
- local timers = {}
- local updating = false
- function TimerBase.Start(time, func, ...)
- return this.StartLoop(time, 1, func, ...)
- end
- function TimerBase.StartLoop(time, count, func, ...)
- local t =
- {
- time = time,
- nextTime = this.GetTime() + time,
- count = count,
- func = func,
- args = spack(...),
- }
- table.insert(timers, t)
- return t
- end
- function TimerBase.StartLoopDelay(delayTime,time, count, func, ...)
- local t =
- {
- time = time,
- nextTime =delayTime<=0 and (this.GetTime() +time) or (this.GetTime()+delayTime),
- count = count,
- func = func,
- args = spack(...),
- }
- table.insert(timers, t)
- if delayTime<=0 then
- t.func(sunpack(t.args))
- end
- return t
- end
- function TimerBase.StartLoopForever(time, func, ...)
- return this.StartLoop(time, -1, func, ...)
- end
- ---@return void @调用开始的时候调用一次func
- function TimerBase.StartLoopForeverBeginCallOnce(time, count,func, ...)
- local t =
- {
- time = time,
- nextTime = this.GetTime() + time,
- count = count,
- func = func,
- args = spack(...),
- }
- table.insert(timers, t)
- t.func(sunpack(t.args))
- return t
- end
- function TimerBase.Stop(t)
- if not t then
- return
- end
- if updating then
- t.count = 0
- else
- local index = array.indexOf(timers, t)
- if index then
- timers[index].isTimerStop = true
- table.remove(timers, index)
- end
- end
- end
- function TimerBase.Update()
- updating = true
- local now = this.GetTime()
- local count = #timers
- local i = 1
- while i <= count do
- local t = timers[i]
- local remove = false
- local needCall = false
- if t.count == 0 then
- remove = true
- elseif t.nextTime <= now then
- needCall = true
- if t.count == 1 then
- remove = true
- else
- if t.count > 1 then
- t.count = t.count - 1
- end
- t.nextTime = t.nextTime + t.time
- end
- end
- if remove then
- table.remove(timers, i)
- t.isTimerStop = true
- count = count - 1
- if needCall then
- t.func(sunpack(t.args))
- end
- if t.completed then
- t.completed()
- end
- else
- if needCall then
- t.func(sunpack(t.args))
- end
- i = i + 1
- end
- end
- updating = false
- end
- function TimerBase.GetTime()
- return 0
- end
- return TimerBase
|