Loop inside a thread still runs even with closed state

I have this Teleport countdown that can be cancelled but when I cancel it, the loop seems still running.

This is my first solution:

task.spawn(function()
	while task.wait(1) do
		if not isTPCancelled then
			MAX_TIME -= 1
			if MAX_TIME == 0 then
				RequestTP:FireServer(true, {"this is my data", 1337, true})
				break
			end
			TPCounter.Text = MAX_TIME
		else
			circularTween:Pause()
			break
		end
	end
end)

This is my current:

TPThread = coroutine.create(function()
	TPCounter.Text = MAX_TIME
	for count = MAX_TIME, 0, -1 do
		TPCounter.Text = count
		if isTPCancelled == true then
			circularTween:Pause()
			coroutine.close(TPThread)
			break
		end
		task.wait(1)
	end
	if isTPCancelled == false then
	    RequestTP:FireServer(true, {"this is my data", 1337, true})
    end
end)
coroutine.resume(TPThread)

I don’t know how to handle coroutines yet so please help me.

Update:
I think the thread is doing fine, its just that the variable isTPCancelled is not changing its value therefore the for-loop is not breaking…

I replaced it with task.spawn() and made the isTPCancelled into an attribute so that it will be a global variable that can be referenced in any line making the cancel script work.

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