Delays and Cooldowns

From Garry's Mod
Revision as of 14:52, 17 May 2017 by JasonMan (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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

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. 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
NOTE

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

Personal tools
Navigation