aboutsummaryrefslogtreecommitdiff
path: root/intervals.lua
blob: 025454db2a0f6789561cd67d74a534016b4fa5f3 (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
31
32
33
34
35
36
37
lua_async.intervals = {
	pool = {},
	executing = {},
	last_id = 0,
}

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

function clearInterval(id)
	lua_async.intervals.pool[id] = nil
	lua_async.intervals.executing[id] = nil
end

function lua_async.intervals.step(dtime)
	lua_async.intervals.executing = table.copy(lua_async.intervals.pool)

	for id, interval in pairs(lua_async.intervals.executing) do
		interval.time_left = timeout.time_left - dtime

		if interval.time_left <= 0 then
			interval.callback(unpack(interval.args))
			interval.time_left = interval.step_time
		end
	end
end