Delays and Cooldowns
A delay (or cooldown) is a way to make an event only trigger if a certain amount of time has passed since its last occurrence.
CurTime is a useful tool for setting a delay for an event. The function returns the uptime of the server in seconds, which means we can use it to keep track of time elapsed by saving the returned value, then calling it again.
Here's an example of an anti chat spam system made using CurTime
local delay = 2 hook.Add( "PlayerSay", "CheckForAntiSpam", function( ply, text ) if not ply.lastChatMessage then ply.lastChatMessage = -delay end -- This is to ensure the first time trigger works properly if CurTime() - ply.lastChatMessage < delay then -- If the time passed since the last message sent is less than 2 seconds ply:ChatPrint( "You must wait " .. delay .. " seconds after sending a chat message to send another one" ) -- Let the player know he can't send the message return "" -- Deny the message else -- If it's been more than 2 seconds since the last message was sent ply.lastChatMessage = CurTime() -- Update lastChatMessage end end )
If your event isn't related to in-game events; consider using RealTime instead, which will always be synced to real-world time rather than server time
In the above example, we use CurTime to tell when the last event had occured. Instead, we could use it to determine when the next event should occur
local delay = 5 local nextOccurance = 0 hook.Add( "Think", "CurTimeDelay", function() if CurTime() > nextOccurance then -- If the time has passed the nextOccurance time print( "This message will repeat every 5 seconds." ) nextOccurance = CurTime() + delay end end )
Another method of setting a delay is using the timer library.
local delay = 2 local shouldOccur = true hook.Add( "PlayerSay", "CheckForAntiSpam", function( ply, text ) if shouldOccur then shouldOccur = false timer.Simple( delay, function() shouldOccur = true end ) else return "" end end )