Delays not working on runservice loops

so i’m trying to make a light color “seizure mode” for my game and it uses a local RunService loop for the randomizer

local RunService = game:GetService("RunService")
RunService.Heartbeat:Connect(function()
	oddrand = Color3.fromHSV(Random.new():NextNumber(0,1), 1, 1)
	evenrand = Color3.fromHSV(Random.new():NextNumber(0,1), 1, 1)
	task.wait(1)
end)

for some reason, the delay i put in there won’t work, even if i set it to something like 10000

(epilepsy warning)

i’ve also tried making this with a while true do loop, but it just won’t work and didn’t show any errors, what should i do?

RunService events like RenderStepped, Stepped and Heartbeat all occur each frame (cycle). That means they will fire and call connected functions every frame, regardless of the code those functions execute. The refresh rate will only be impacted by frame rate.

:Connect() also spawn individual lua threads, therefore all those functions are called separately each time. A function bound to the refresh cycle won’t yield the update (unless of course it’s so performance intensive it causes lag and reduces frame rate).

A loop would be more suitable in your case.

i’ve tried using while true do and while wait() do loops but for some reason the light colors just stay black, and it gave no error indication at all

In that case, the problem must be hiding somewhere else. Perhaps there are multiple loops, and the discussed loop is never reached.

-- continuous loop 1
-- loop 2 not reached
local RandomGen = Random.new()
while condition do
	oddrand = Color3.fromHSV(RandomGen:NextNumber(0,1), 1, 1)
	evenrand = Color3.fromHSV(RandomGen:NextNumber(0,1), 1, 1)
	-- update the colors
	task.wait(1)
end

Maybe coroutines or task.spawn(function() end) can help you run the code synchronously.

1 Like

okay, now it works, thanks! (also apparently i’ve done that before just realized that i forgot to enable the script)

1 Like