-
Notifications
You must be signed in to change notification settings - Fork 0
/
sleep.lua
57 lines (43 loc) · 1.36 KB
/
sleep.lua
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
-- Emulate a sleep function.
-- Instead of sleeping, this makes the current thread yield
-- Super hacky, but should get us going fast. Ideally this should use "piping"
js = require"js"
local sleep = {}
function sleep.sleep(s)
-- Call this from within a thread to send it to sleep.
coroutine.yield(s)
end
local sleeper = {}
sleeper.__index = sleeper
function sleeper:_launch()
local exit_st, delay_or_err = coroutine.resume(self.coro)
if not self.cancel_request and exit_st and delay_or_err then
self.timer_id = js.global.window:setTimeout(function () sleeper._launch(self) end, delay_or_err*1000)
else
self.timer_id = nil
if not exit_st and self.onerror then
self:onerror(delay_or_err)
end
end
end
function sleeper:launch()
self.cancel_request = nil
self:_launch()
end
function sleeper:new(f, error_cb)
-- Create a thread from a function f that can call sleep.sleep(s)
return setmetatable({coro=coroutine.create(f), onerror=error_cb}, sleeper)
end
function sleeper:cancel()
-- cancel a task
self.cancel_request = true
tid = self.timer_id
if tid then
js.global.window:clearTimeout(tid)
end
end
sleep.sleeper = sleeper
local riot = {sleep=sleep.sleep}
-- return sleep
package.preload.sleep = function() return sleep end
package.preload.riot = function() return riot end