Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 4 years ago
Edited 4 years ago

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)


0
Did you try "wait(3)"? lopte1 -5 — 4y
0
Yeah that's what I did and it just waited 3 seconds before bombarding you with the spams xD adamson239 12 — 4y

1 answer

Log in to vote
1
Answered by 4 years ago

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.

0
I KNEW I SHOULD'VE USED DEBOUNCE omg thank you xD adamson239 12 — 4y
Ad

Answer this question