Delays and Cooldowns

From Garry's Mod
Revision as of 15:45, 17 May 2017 by JasonMan (Talk | contribs)
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.

Creating an event cooldown

An event cooldown can be created in several ways, and it is made by setting a condition based on time

function myFunc()
	if funcNotOnCooldown then
		-- Do stuff
	end
end

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 elapsed by saving the returned value, then calling it again.

Here's an example of a cooldown made using CurTime

local delay = 2
local lastOccurance = -delay -- Ensure the first trigger attempt will work
local function myFunc()
	local timeElapsed = CurTime() - lastOccurance
	if timeElapsed < delay then -- If the time elapsed since the last occurance is less than 2 seconds
		print( "The event is on cooldown and has not been triggered" )
		print( "Please wait another " .. math.Round( delay - timeElapsed ) .. " second(s)" )
	else
		print( "The event has been triggered!" )
		lastOccurance = CurTime()
	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

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

local function myFunc()
	local timeLeft = nextOccurance - CurTime()
	if timeLeft < 0 then -- If the time has passed the nextOccurance time
		print( "The event has been triggered!" )
		nextOccurance = CurTime() + delay
	else
		print( "The event is on cooldown and has not been triggered" )
		print( "Please wait " .. math.Round( timeLeft ) .. " second(s)" )
	end
end )

Timers

Another method of setting a delay is using the timer library.

local delay = 2
local shouldOccur = true

local function myFunc()
	if shouldOccur then
		print( "The event has been triggered!" )
		shouldOccur = false
		timer.Simple( delay, function() shouldOccur = true end )
	else
		print( "The event is still on cooldown" )
	end
end
Personal tools
Navigation