Task.cancel() not working

game:GetService("Players").PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(character)
		game:GetService("RunService").Heartbeat:Connect(function()
			script.Parent.HumanoidRootPart.CFrame = CFrame.lookAt(script.Parent.PrimaryPart.Position, Vector3.new(character.PrimaryPart.Position.X, script.Parent.PrimaryPart.Position.Y, character.PrimaryPart.Position.Z))
			
			local thread = task.spawn(function()
				if (script.Parent.PrimaryPart.Position - character.PrimaryPart.Position).Magnitude <= 9 and cooldown == false then
					cooldown = true
					task.wait(3)
					if (script.Parent.PrimaryPart.Position - character.PrimaryPart.Position).Magnitude <= 9 then
						print("hello")
					end
				end
			end)
			
			
			if (script.Parent.PrimaryPart.Position - character.PrimaryPart.Position).Magnitude > 9 and cooldown == true then
				print("canceled")
				cooldown = false
				
				if thread then
					task.cancel(thread)
				end
			end
			
		end)
	end)
end)

this is the code I have. I have a noob that watches the player. I also tried making a check that if player stands close enough then noob will do something funny. I tried doing this thought task library but the only thing that I don’t understand is that task.cancel just doesn’t cancel the function.

It does print cancel when I walk back from npc but if I walk to him again in the time of this 3 seconds, then the function would still work. Does task.cancel pauses the thread or something then?
Sorry if this is confusing.

I’m not sure exactly what you’re trying to accomplish but spawning a thread every heartbeat feels wrong.
It seems like you would want a single heartbeat connection that looks for the closest player within your desired range and looks at that player’s character.