How do i make a cooldown that resets itself?

So, I have a basic custom chat script that detects when the player scripts and sets a billboard gui to be that specific text. After 10 seconds the text will dissapear, However when a second message is sent, the script is still running so the timer will not restart and the text will clear early:

local cooldown = 10

game.Players.PlayerAdded:Connect(function(Player)
	Player.Chatted:Connect(function(msg)
		workspace.Characters[Player.Name].Head.TextBar.Chat.Text = msg
		wait(cooldown)
		workspace.Characters[Player.Name].Head.TextBar.Chat.Text = ""
	end)
end)

Any help/tips to allow it to reset everytime it detects another chat message?

1 Like

i would recommend having an “id” to describe the current event. If the id is not the same at the end of the script then stop the script.

Example:

local currentId = nil
Player.Chatted:Connect(function(msg)
	-- use tick instead of random to prevent a small chance of it being the same
	-- instead it'll be the current time which will never be the same
	local myId = tick()
	currentId = myId

	wait(myCooldown)

	-- if the code ran again then the currentId would be different
	if currentId ~= myId then
		return
	end

	-- run cleanup code here
end)
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.