aboutsummaryrefslogtreecommitdiff
path: root/timeouts.lua
blob: b3b69e8a659ed64d51d28af6d1180eee66a1da17 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
lua_async.timeouts = {
	pool = {},
	last_id = 0,
}

function setTimeout(callback, ms, ...)
	local id = lua_async.timeouts.last_id + 1
	lua_async.timeouts.last_id = id
	lua_async.timeouts.pool[id] = {
		time_left = (ms or 0) / 1000,
		callback = callback,
		args = {...},
	}
	return id
end

function clearTimeout(id)
	lua_async.timeouts.pool[id] = nil
end

function lua_async.timeouts.step(dtime)
	for id, timeout in pairs(lua_async.timeouts.pool) do
		timeout.time_left = timeout.time_left - dtime

		if timeout.time_left <= 0 then
			timeout.callback(unpack(timeout.args))
			clearTimeout(id)
		end
	end
end