Lesson 6: Work with timers
Goal: a /remind command and a repeating timer you cancel yourself.
--! name: Reminder--! description: /remind says "time is up" after a minute--! api: 1--! permissions: sendswizzin.command("remind", function(ctx, args) local target = ctx.target if target == nil then return end swizzin.timer.after(60000, function() swizzin.send(target, "Time is up") end)end, "Remind this channel in one minute")
-- a repeating timer that stops itself after 3 runslocal runs = 0local idid = swizzin.timer.every(1000, function() runs += 1 swizzin.log("tick", runs) if runs >= 3 then swizzin.timer.cancel(id) endend)What it does
Section titled “What it does”timer.after(ms, fn) runs once (0 to 86,400,000 ms). timer.every(ms, fn) repeats (at least 100 ms). timer.cancel(id) stops one. A timer keeps the network context it was created in.
Expected result
Section titled “Expected result”/remind in a channel sends Time is up there a minute later. The Console shows tick 1, tick 2, tick 3 once per second after the script loads.
Common mistakes
Section titled “Common mistakes”- Never cancelling repeating timers: a script may have at most 32, and all stop when the script stops.
- Reading
ctxlater: copy what you need (liketarget) into a local first. - Slow timer callbacks: each must finish within 250 ms.
Troubleshooting
Section titled “Troubleshooting”- Nothing fires: confirm the script is On and check the Console for errors.