Hello everyone! I was wondering how can I run a function for a certain amount of time?
I have a function that fires whenever a player touches a part, but I want it to fire only for 15 seconds. Then after the 15 seconds it can’t fire anymore.
I’ve tryied something like this, but it is pretty unefficient:
local canRun = true
local part = workspace.Part
local a = coroutine.wrap(function()
wait(15)
canRun = false
end
a()
while canRun == true do
part.Touched:Connect(function()
--- Function here
end
end
Disconnect the event after the 15 seconds has elapsed; This should make the event stop listening for touches:
local con;
con = part.Touched:Connect(function()
end)
wait(15)
con:Disconnect()
This is worth mentioning - while loops require some yield, like a wait, or else your game will crash. You are also creating a lot of connections that listens for the touched event, so the function in the event would occur many times. Not to mention memory leaks because of the number of connections you’re making in the loop. Avoid doing something like this