Task.cancel() isn't working

Trying to make a script that plays footstep sounds, but only if you walk for .3 seconds (to disable jittering of the sound)

        local TaskFunction = nil
	Human.Running:Connect(function(speed)
		if speed < 25 and speed > 1 then
			TaskFunction = task.delay(.3, function()
				if WalkSound.IsPlaying then return end
				playSound(WalkSound)
				print("Debug")
			end)
			
		elseif speed <= 1 then
			stopSound(WalkSound)
			if TaskFunction then	
			
				task.cancel(TaskFunction)
				TaskFunction = nil
				
				print("Stopping Task")
			end
		end
	end)

It’s printing “Stopping Task”; and it doesn’t actually cancel the TaskFunction for some reason?

External Media
1 Like

To stop a Sound from playing you’ll need to use the :Stop() method, cancelling the thread won’t stop looped sounds from playing

Also in your case, you’ll probably need to create a separate thread for the playSound function using task.spawn and cancel that thread instead of the one you’re currently canceling

1 Like

yeah you’re not understanding, i fixed the issue though by adding a check if taskfunction exists then returning:

local TaskFunction = nil
	Human.Running:Connect(function(speed)
		if speed < 25 and speed > 1 then
			if TaskFunction then return end
			TaskFunction = task.delay(.2, function()
				playSound(WalkSound)
			end)
			
		elseif speed <= 1 then
			stopSound(WalkSound)
			
			if TaskFunction then	
				task.cancel(TaskFunction)
				TaskFunction = nil

			end
		end
	end)
2 Likes

That’s a good observation actually, well done! :grin::+1:

I focused too much on why task.cancel wasn’t working which is why I said what I said :sweat_smile:

2 Likes

Yeah so when i was printing in .Running, it always did it 2 times, so i wondered if it made the task 2 times and it seems like i was right.

2 Likes

By the way, a neat way to write this:

TaskFunction = task.delay(.2, function()
	playSound(WalkSound)
end)

is by doing this:

TaskFunction = task.delay(0.2, playSound, WalkSound)

It has the benefit of saving an extra function call

1 Like

Dang thanks, i actually really appreciate this. Thanks!

1 Like

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