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?
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
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)
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).