How do I make this car spawner script have a cooldown?

Hello. I did not make this script, however I would like to edit it so that it has a cooldown.
So basically this script works to spawn a car when the user clicks the button in-game. I would like to add a “cool-down”, as users can spam click the button and multiple cars will instantly spawn, lagging the game server. Would anyone know how to make this script make it so the user can spawn the car only every 5-10 seconds? (if possible)

Screen Shot 2020-03-17 at 18.47.31

6 Likes

What I usually do is:

local stop = 1
script.Parent.MouseButton1Click:Connect(function(GetCar)
if stop == 1 then
stop = 0
--car stuff
wait(5)
stop = 1
end)
2 Likes

Debounces would help solve issues like this.

local Debounce = false
script.Parent.MouseButton1Click:connect(function(GetCar)
     if Debounce == false then
          Debounce = true
          Mod = game.ServerStorage.RedCar
          clone = Mod:clone()
          clone.Parent = workspace
          clone:MakeJoints()
          wait(5)
          Debounce = false
     end
end)
8 Likes

You could also just disable the button and hide it from the player.

script.Parent.MouseButton1Click:Connect(function(GetCar)
	Mod = game.ServerStorage:WaitForChild("RedCar")
	Mod:Clone().Parent = workspace
	Mod:MakeJoints()
	script.Parent.Visible = false
	wait(5)
	script.Parent.Visible = true
end)
4 Likes

Instead of using wait(..), an alternative method could be to compare the server’s tick() value against a variable value, where this variable value determines the next available time that spawning a car is allowed.

By avoiding wait(), there won’t be any lingering / pending / unfinished methods running, which takes up resources.

Here is an alternative “debounce implementation”:

-- Server-side script
local nextCarAvailableAtTick = tick() -- Initialize

local function TrySpawnCar()
  local nowTick = tick()
  if nextCarAvailableAtTick <= nowTick then
    nextCarAvailableAtTick = nowTick + 10 -- Set it to 10 seconds from now
    SpawnCar() -- Some function elsewhere, that does the actual spawning of a car
  end
end

script.Parent.MouseButton1Click:Connect(function()
  TrySpawnCar()
end)
5 Likes