Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Is there a way to add a cooldown to a button?

I'm trying to make it so when a player clicks a button the button waits for 3 seconds before it can work again but every time I tried to do it if the player spam clicks it the function still gets spammed, is there any way to add a cooldown to when the button can be pressed?

Discord: Unknown Intelligence#6569

local bool = true

local Players = game:GetService("Players")
 
Players.PlayerAdded:Connect(function(player)
	local light = game:GetService("Lighting")
light.TimeOfDay = 1
light.FogEnd = 50
light.FogStart = 20
light.Brightness = 0
light.FogColor = Color3.new(0,0,0)
	
end)


function onMouseClick()

if bool == true then
local light = game:GetService("Lighting")
script.Lightson:Play()
light.TimeOfDay = 12
light.FogEnd = 1000000
light.FogStart = 0
bool = false
	else if bool == false then
	local light = game:GetService("Lighting")
script.Lightsoff:Play()
light.TimeOfDay = 1
light.Brightness = 0
light.FogColor = Color3.new(0,0,0)
light.FogEnd = 50
light.FogStart = 25
bool = true
end
end
end
		script.Parent.ClickDetector.MouseClick:connect(onMouseClick)


2 comments

0

Did you try "wait(3)"?

0

Yeah that's what I did and it just waited 3 seconds before bombarding you with the spams xD

1 answer

✓ Accepted answer

In the scripting world, we call this "debounce". Don't ask me why, the Code Gods just made it like that. Before your function, add a variable called "debounce" and set it to false. Then when the function is ran, set the debounce as true with a wait time of three seconds (or whatever you want). It'll look something like what I have below.

local debounce = false

function onMouseClick()
if not debounce then
	debounce = true
	if bool == true then
	local light = game:GetService("Lighting")
	script.Lightson:Play()
	light.TimeOfDay = 12
	light.FogEnd = 1000000
	light.FogStart = 0
	bool = false
	    else if bool == false then
	    local light = game:GetService("Lighting")
	script.Lightsoff:Play()
	light.TimeOfDay = 1
	light.Brightness = 0
	light.FogColor = Color3.new(0,0,0)
	light.FogEnd = 50
	light.FogStart = 25
	bool = true
	end
	end
	end
	wait(3)
	debounce = false
end
	        script.Parent.ClickDetector.MouseClick:connect(onMouseClic

Sorry if the script is badly formatted and organized, writing this on mobile xD.

1 comment

0

I KNEW I SHOULD'VE USED DEBOUNCE omg thank you xD

This discussion is preserved as it was. New answers, comments, and votes are closed.