]> git.lizzy.rs Git - lua_async.git/blob - intervals.lua
Safe interval implementation
[lua_async.git] / intervals.lua
1 lua_async.intervals = {
2         pool = {},
3         executing = {},
4         last_id = 0,
5 }
6
7 function setInterval(callback, ms, ...)
8         local id = lua_async.intervals.last_id + 1
9         lua_async.intervals.last_id = id
10         local step_time = (ms or 0) / 1000
11         lua_async.intervals.pool[id] = {
12                 time_left = step_time,
13                 step_time = step_time,
14                 callback = callback,
15                 args = {...},
16         }
17         return id
18 end
19
20 function clearInterval(id)
21         lua_async.intervals.pool[id] = nil
22         lua_async.intervals.executing[id] = nil
23 end
24
25 function lua_async.intervals.step(dtime)
26         lua_async.intervals.executing = table.copy(lua_async.intervals.pool)
27
28         for id, interval in pairs(lua_async.intervals.executing) do
29                 interval.time_left = timeout.time_left - dtime
30
31                 if interval.time_left <= 0 then
32                         interval.callback(unpack(interval.args))
33                         interval.time_left = interval.step_time
34                 end
35         end
36 end
37