[Solved] Adding a wait() to RunService.Heartbeat

Hello,

I’m currently writing some code using RunService.Heartbeat though I would like for the code to wait 1 second after a point is given.

Example:

local Points = 0

game:GetService("RunService").Heartbeat:Connect(function()
	Points += 1
	wait(1)
end)

But obviously just adding wait() will not work, and so I added a debounce:

local Points = 0
local Debounce = false

game:GetService("RunService").Heartbeat:Connect(function()
	if Debounce then return end
	Debounce = true
	
    Points += 1

	wait(1)
	Debounce = false
end)

Is this the best way to do it? Or even the only way to do it?

Thanks

I don’t think there is another method but there is a reason why you want to avoid debounce?

If you need a loop to run every second then use “while task.wait(1) do” instead as RunService.Heartbeat fires every frame (1/60th of a second).

local Run = game:GetService("RunService")

--every frame one second after the script executes the print command is ran
Run.Heartbeat:Connect(function()
	task.wait(1)
	print("Hello world!")
end)

--every second the print command is ran
while task.wait(1) do
	print("Hello world!")
end

Here’s a comparison.

1 Like

You can use tick() or any similar function to know if a second has passed inside a Heartbeat event, but I don’t really get why you can’t just use a while loop for this.

local Points = 0
local LastTime = tick()

game:GetService("RunService").Heartbeat:Connect(function()
	if tick()-LastTime < 1 then return end
	LastTime = tick()
	Points += 1
end)
2 Likes

Thing is, I’d like to be able to disconnect from heartbeat at some point this is why it wouldn’t be fitting. Thanks for the reply though!

You can break out of while loops using break

If you want to run it on the background use coroutines or task.spawn()

1 Like

As the previous post suggested you could just do the following.

local condition = nil --example

task.spawn(function()
	while true do
		task.wait(1)
		if condition then
			--perform code
		else
			break
		end
	end
end)
2 Likes

The problem with this is you’re connecting an event which is fired every frame to an anonymous callback function (a new closure value) for something which only needs to be executed once per second (which is highly inefficient).

2 Likes