I need to be able to stop a heartbeat loop from running and be able to start it again. Apparently disabling/undisabling the script doesn’t work for this because the current thread will continue running, so a heartbeat does not stop when the script is disabled.
This seems to work and completely stops the heartbeat from running and then enabling the script will start the heartbeat again, but I’m concerned, could this create a memory leak if I continue to repeatedly disable/undisable the script?
RunService.Heartbeat:Connect(function(step)
if script.Disabled == true then
return -- stops the heartbeat when the script is disabled
end
-- normal coding that would run every frame if the script is not disabled
end)
you can set a variable to the connection like this:
heartbeatConnection = RunService.Heartbeat:Connect(function(step)
You can then disconnect a connection like this:
heartbeatConnect:Disconnect()
Some things to note here, you want to make sure you disconnect a connect before you make a new one, or you can lose your reference when you set a new connection to an existing variable. Another thing, you’ll probably want to set connection variables to nil after you are done, and check if they exist before you try disconnecting them.
For making this accessible to other scripts, you could make this code in a module, and require it by other scripts. Or I’d suggest using attributes and attribute changed signals to enable/disable your connections.
3 Likes
As VitalWinter mentioned, the only way would be to call :Disconnect()
on the RBXConnection of the Heartbeat.
local rbxCon;
rhxCon = RunService.Heartbeat:Connect(function(step)
if ((script.Disabled == true) and rbxCon) then
rbxCon:Disconnect(); -- stops the heartbeat when the script is disabled
return;
end
-- normal coding that would run every frame if the script is not disabled
end)
Learn more about ROBLOX connections here.
4 Likes