Debounce doesn't work properly

I’m trying to make a system that spawns random events for a certain amount of time, and after the time is over that event should stop, but it doesn’t, the events just keep stacking and never stopping.

local runService = game:GetService("RunService")

local isInRound = game.ReplicatedStorage.IsInRound

local eventTime = 15
local timer = 0

local events = {}

events[1] = {
	name = "Meteor Shower", 
	f = function()
		local debounce = true
		spawn(function()
			wait(eventTime)
			debounce = false
		end)
		while debounce do
			local spawns = game.Workspace.SkyEventSpawns:GetChildren()

			while wait(0.5) do
				local randomPos = spawns[math.random(1, #spawns)]
				local meteorClone = game.ReplicatedStorage.Meteor:Clone()
				meteorClone.Parent = workspace
				meteorClone.PrimaryPart.Position = randomPos.Position
			end
			wait()
		end
	end
}

events[2] = {name = "Zombie Apocalypse", 
	f = function()
		local debounce = true
		spawn(function()
			wait(eventTime)
			debounce = false
		end)
		while debounce do
			local spawns = game.Workspace.Targets:GetChildren()

			for _, spawnPoint in pairs(spawns) do
				local spawnPos = spawnPoint.Position
				local zombie = game.ReplicatedStorage.Zombie:Clone()
				zombie.Parent = workspace
				zombie:WaitForChild("Charcter"):FindFirstChild("HumanoidRootPart").CFrame.Position = spawnPos
			end
			wait()
		end
	end
}

runService.Heartbeat:Connect(function(dt)
	if isInRound.Value == true then
		timer += dt

		if timer > eventTime + 2 then
			timer = timer % eventTime

			local event_index = math.random(#events)

			local event = events[event_index]
			local event_name = event.name
			local event_f = event.f

			print("There is a " .. event_name)
			event_f()
		end
	end
end)

This while loop is running indefinitely.

Instead:

while task.wait(0.5) do
	if debounce == false then
		break
	end
-- ...
end

Make sure that you check the debounce and break the loops in your other events as well.

Also, wait and spawn are deprecated, use task.wait and task.spawn instead.

2 Likes

Pretty sure you have a typo for character

2 Likes

Thanks, I didn’t notice I had a typo