Lua setTimeout/clearTimeout

Date: 2018-07-14
local uv = require('luv')

local function sleep(delay, thread)
  thread = thread or coroutine.running()
  local timer = uv.new_timer()
  uv.timer_start(timer, delay, 0, function ()
    uv.timer_stop(timer)
    uv.close(timer)
    return assert(coroutine.resume(thread))
  end)
  return coroutine.yield()
end

local function setTimeout(delay, callback, ...)
  local timer = uv.new_timer()
  local args = {...}
  uv.timer_start(timer, delay, 0, function ()
    uv.timer_stop(timer)
    uv.close(timer)
    callback(unpack(args))
  end)
  return timer
end

local function setInterval(interval, callback, ...)
  local timer = uv.new_timer()
  uv.timer_start(timer, interval, interval, bind(callback, ...))
  return timer
end

local function clearInterval(timer)
  if uv.is_closing(timer) then return end
  uv.timer_stop(timer)
  uv.close(timer)
end

local clearTimeout = clearInterval

setTimeout(2000, function()
    print 'Timed out'
end);

print 'running uv'
uv.run()
print 'finished'

11660cookie-checkLua setTimeout/clearTimeout