summaryrefslogtreecommitdiffstatshomepage
path: root/3rdparty/luv/examples/timers.lua
blob: 049235e6fb191e5514fc2e104a59767eb6fccb9f (plain) (blame)
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
57
58
59
60
61
62
63
64
65
66
67
68
local p = require('lib/utils').prettyPrint
local uv = require('luv')

local function set_timeout(timeout, callback)
  local timer = uv.new_timer()
  local function ontimeout()
    p("ontimeout", timer)
    uv.timer_stop(timer)
    uv.close(timer)
    callback(timer)
  end
  uv.timer_start(timer, timeout, 0, ontimeout)
  return timer
end

local function clear_timeout(timer)
  uv.timer_stop(timer)
  uv.close(timer)
end

local function set_interval(interval, callback)
  local timer = uv.new_timer()
  local function ontimeout()
    p("interval", timer)
    callback(timer)
  end
  uv.timer_start(timer, interval, interval, ontimeout)
  return timer
end

local clear_interval = clear_timeout

local i = set_interval(300, function()
  print("interval...")
end)

set_timeout(1000, function()
  clear_interval(i)
end)


local handle = uv.new_timer()
local delay = 1024
local function ontimeout()
  p("tick", delay)
  delay = delay / 2
  if delay >= 1 then
    uv.timer_set_repeat(handle, delay)
    uv.timer_again(handle)
  else
    uv.timer_stop(handle)
    uv.close(handle)
    p("done")
  end
end
uv.timer_start(handle, delay, 0, ontimeout)


repeat
  print("\ntick.")
until uv.run('once') == 0

print("done")

uv.walk(uv.close)
uv.run()
uv.loop_close()