How to run a function for a certain amount of time?

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

Have you got any idea on how to achieve this?

2 Likes

Quite don’t understand, I mean, why would you need a function that rusn every 15 seconds? Just make the thing you have to do in 15 seconds?
:thinking:

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

4 Likes

Thank you! That’s what I was looking for!