]> git.lizzy.rs Git - lua_async.git/blob - timeouts.lua
Fix some small mistakes in the documentation of clearImmediate
[lua_async.git] / timeouts.lua
1 lua_async.timeouts = {
2         pool = {},
3         executing = {},
4         last_id = 0,
5 }
6
7 function setTimeout(callback, ms, ...)
8         local id = lua_async.timeouts.last_id + 1
9         lua_async.timeouts.last_id = id
10         lua_async.timeouts.pool[id] = {
11                 time_left = (ms or 0) / 1000,
12                 callback = callback,
13                 args = {...},
14         }
15         return id
16 end
17
18 function clearTimeout(id)
19         lua_async.timeouts.pool[id] = nil
20         lua_async.timeouts.executing[id] = nil
21 end
22
23 function lua_async.timeouts.step(dtime)
24         lua_async.timeouts.executing = lua_async.timeouts.pool
25         lua_async.timeouts.pool = {}
26
27         for id, timeout in pairs(lua_async.timeouts.executing) do
28                 timeout.time_left = timeout.time_left - dtime
29
30                 if timeout.time_left <= 0 then
31                         timeout.callback(unpack(timeout.args))
32                 else
33                         lua_async.timeouts.pool[id] = timeout
34                 end
35
36                 lua_async.timeouts.executing[id] = nil
37         end
38 end