Snippet: Simpler timers using coroutines

Here’s a nifty way of using coroutines that can greatly simplify certain kinds of scheduling code:

local sleep = coroutine.yield -- Syntactic sugar

local function schedule(fn, when)
  local co = coroutine.wrap(fn)

  local timer
  timer = function()
    renoise.tool():remove_timer(timer)
    local delay = co()
    if not delay then
      return
    end
    renoise.tool():add_timer(timer, delay)
  end

  renoise.tool():add_timer(timer, when)
end

-- Let's test it out:

local function slowdown()
  for i = 1, 5 do
    print(i)
    sleep(i * 100)
  end
end

schedule(slowdown, 100)
1 Like