aboutsummaryrefslogtreecommitdiff
path: root/intervals.lua
blob: 72a0cc74135189e58b42e39551c8a9632ccbfa89 (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
lua_async.intervals = {
	pool = {},
	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
end

function lua_async.intervals.step(dtime)
	for id, interval in pairs(lua_async.intervals.pool) 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