Trying to make a countdown without yielding the script

I have a mining system with a health bar above the nod. I use a LOCAL SCRIPT
I want to Enable the HealthBar when the player hits the nod. However, after 3 seconds WITHOUT hitting the nod. The healthbar Disables (disappears). Each time the nod has been hit, the “timer” restarts.

I tried something like this, but it yields for 3s. What would be the best way to do it? The timer is inside an if statement btw

					elseif touching_part.Parent:IsA("Folder") and touching_part.Parent.Parent.Name == "Nods" then
						Mining_Damage_Event:FireServer(touching_part, Pickaxe:GetAttribute("PickaxeLevel"))
						--[[local HealthBar = touching_part:FindFirstChildWhichIsA("BillboardGui")
						
						local TimeWhereMined = os.time()
						if not HealthBar.Enabled then
							HealthBar.Enabled = true
							if TimeWhereMined - os.time() >= 3 then
								HealthBar.Enabled = false
							end
							
						end]]
``` I commented out the part that I tried

Thank you

Use task.defer or coroutines to create threads that run alongside the rest of the script

task.defer(function()
  -- do countdown
end)
1 Like

whats the difference between task.spawn() and task.defer()

2 Likes

Or if you want to use a low budget method try enabling a script which does the countdown on its own, which I used back in my horrible scripting days

task.spawn runs the function as soon as it can with the scheduler

task.defer runs the function at the next possible cycle, so use task.spawn when speed is really neccessary.

there are usually around 60 cycles a second

1 Like