Skip to content

Commit

Permalink
feat(timer): add timer package
Browse files Browse the repository at this point in the history
  • Loading branch information
lukadev-0 committed Feb 28, 2024
1 parent bbab94c commit 87990ef
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
6 changes: 6 additions & 0 deletions packages/timer/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
name = "timer"
description = "Schedule functions to be called at a future time."
version = "1.0.0"

bundle = "timer"
dependencies = ["env", "future", "threadpool"]
30 changes: 30 additions & 0 deletions packages/timer/init.luau
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
local Future = require("../future")
local env = require("../env")
local threadpool = require("../threadpool")

local task = env.libs.task

local timer = {}

function timer.delay(duration: number): Future.Future<number>
return Future.spawn(task.wait, duration)
end

function timer.interval<T...>(duration: number, f: (T...) -> (), ...: T...): () -> ()
-- selene: allow(shadowing)
local function inner(duration: number, f: (T...) -> (), ...: T...)
local nextTick = os.clock() + duration
while true do
task.wait(nextTick - os.clock())
threadpool.spawn(f, ...)
nextTick += duration
end
end

local thread = task.spawn(inner, duration, f, ...)
return function()
task.cancel(thread)
end
end

return timer

0 comments on commit 87990ef

Please sign in to comment.