Only one instance of a function running, and a new instance can be created at any time

Hi,

I use this coding pattern a lot in my projects, but it’s really clunky to set up.
I’m wondering if there’s a better way to set it up.

Current pattern I have set up.

local jobID = 0
local function foo()
	--[[
	Requirements of this function:
		- only one instance of it should be running at any time
		- the function can be called at any time, usually it'll be called during its yield of task.wait() periods
		- if the function is already running and a new one is called, exit the old one
	--]]
	
	jobID = jobID + 1
	local currentJobID = jobID
	
	print("One", jobID)
	task.wait(1)
	if currentJobID ~= jobID then return end
	
	print("Two", jobID)
	task.wait(1)
	if currentJobID ~= jobID then return end
	
	print("Three", jobID)
end

for i = 1,10 do
	task.defer(function() 
		-- here we use task.defer, but in the real world case, foo() is usually called by multiple connected events
		foo()
	end)
	wait(0.25) -- we call the function faster than it's able to complete itself
end

Required Output:

  One 1
  One 2
  One 3
  One 4
  One 5
  One 6
  One 7
  One 8
  One 9
  One 10
  Two 10
  Three 10

Ok, closure on this. This can be achieved by using task.cancel().

local function fooReal(i)
	print("One", i)
	task.wait(1)

	print("Two", i)
	task.wait(1)

	print("Three", i)
end

local activeFoo
local function foo(...)
	--[[
	Requirements of this function:
		- only one instance of it should be running at any time
		- the function can be called at any time, usually it'll be called during its yield of task.wait() periods
		- if the function is already running and a new one is called, exit the old one
	--]]
	
	if activeFoo then
		task.cancel(activeFoo)
		activeFoo = nil
	end
	
	activeFoo = task.spawn(fooReal, ...)
end

for i = 1,10 do
	task.defer(function() 
		-- here we use task.defer, but in the real world case, foo() is usually called by multiple connected events
		foo(i)
	end)
	wait(0.25) -- we call the function faster than it's able to complete itself
end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.