How would I go on cancelling a timer or a task/function (See Details Below)

Currently I am making a real-time strategy game and I am focusing on the conquering provinces part. I am having a rough time because I cant seem to get the cancelling part working, basically within the time period (time.delay), if the Unit moves, there would be a part where the timer would be stopped and cancelled(making it not proceed further into the code below.) and will not conquer the province since the unit moved somewhere else.

I need help in making the right form of function to cancel the timer once the unit moves or else the province would be conquered while the troop is moving and would be grateful for any feedback, advice, and overall help, thanks.

local Execute = task.delay(PathPoint.Owner.Value.Parent.DevelopmentLevel.Value, function()
							PathPoint.Owner.Value.Parent.Occupied.Value = true
							PathPoint.Owner.Value.Parent.Owner.Controller.Value = Unit.Detector.Country.Value
							for _, Country in pairs(CounriesFolder:GetChildren()) do
								if Unit.Detector.Country.Value == Country.Name then
									PathPoint.Owner.Value.Parent.Color = Country.CountryColor.Value
								end
							end

							UnitAmount.Value = UnitAmount.Value - math.floor(Population.Value / UnitMaxAmount.Value * 10)
							Population.Value = Population.Value - math.floor(Population.Value / UnitAmount.Value)
							if UnitAmount.Value < 0 then
								UnitAmount.Value = 0
							end
							if Population.Value < 0 then
								Population.Value = 0
							end

							UnitOverhead.Frame.Amount.Text = "[ ".. comma_value(UnitAmount.Value) .." / ".. comma_value(UnitMaxAmount.Value) .." ]"
							UnitOverhead.Frame.ConquerBar.Visible = false

							Unit.Detector.Target.Value = nil
							Unit.Detector.City_Captured:Play()
						end)

						if Unit.Humanoid.MoveDirection.Magnitude > 0 then
							task.cancel(Execute)
							UnitOverhead.Frame.ConquerBar.Visible = false
							print("Cancelled")
							return
						else
							while Unit.Humanoid.MoveDirection.Magnitude <= 0 do
								wait()
							end
						end

How are you going about cancelling the thread and is PathPoint.Owner.Value.Parent.DevelopmentLevel.Value a number?

local Thread = task.delay(PathPoint.Owner.Value.Parent.DevelopmentLevel.Value, function()
-- Code
end)

local BindableEventConnection = UnitMove.Event() -- Connection connected to a bindable event
task.cancel(Thread)
end 
1 Like

Try using a Maid module and clean up the process.

1 Like

Heres the thing, development level is supposed to indicate the development of a State. For now, DevelopmentLevel ranges from 1 to 5.

1 Like

Could you tell me a little bit about what the code in the task.delay() does?
And how you are going about cancelling the thread?