What method should I use for this simple task?

I am trying to play and stop an animation after 0.2 seconds, and my typical method would have been to wait(0.2) then Anim:Stop(0.2) but I am learning many proper methods of coding. I’d like to know what method works best or learn the ‘best’ method.

For context, this animation would be practically used constantly as it’s like an E to interact animation.

I know of these methods:

wait(0.2) --(apparently sucks?)
task.wait(0.2) --(doesn't suck but shouldn't be used?)
delay(0.2,func) --(should be avoided or unreliable?)
Anim.KeyframeReached --(but then I'd have to disconnect the function and nil it)

I’d like to learn more methods or untangle all this confusion.

Are you stopping it at a key frame? Or is 0.2 an arbitrary number?

The idea is to run :Stop(0.2) at the 0.2 second mark, and I’d have that 0.2s keyframe named “Stop”

To clarify, spawn() and delay() both use wait() and they all “suck” compared to task. They run at 30 Hz, yield, and are now considered unreliable, especially when used in large amounts across the game. Now, task.spawn(), task.defer(), task.delay() are consistent and reliable. (task | Roblox Creator Documentation)

task.wait() equals RunService.Heartbeat:Wait().

Another important distinction: task.delay(), task.defer() and task.spawn() all run in separate lua threads. task.wait() actively halts the current one.

:Connect() and :Once() will do that too.

If you have something similar to

UIS.InputBegan:Connect(function(input, gameProcessed)
	if gameProcessed then return; end
	
	if input.UserInputType == Enum.UserInputType.Keyboard then
		if input.KeyCode == Enum.KeyCode.E then
			animation:Play()
			-- what to do here?
		end
	end
end)
-- Why not another event connected a single time?
animation.KeyframeReached:Connect(function(keyframeName)
	if keyframeName == "Stop" then
		animation:Stop(0.2)
	end
end)

PS: I am still not sure when :Once() was introduced, but I like it.

Edit. I may not have said this clearly enough, animation.KeyframeReached is outside of UIS.InputBegan scope. “Connected once” as its own code block.

1 Like

You’re so right about that, using event connected a single time. I’ve also never heard of :Once() and that’s so good, no more having to disconnect once time events! thank you so much.

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