How can I check if a while task.wait() do loop has finished waiting

i have a consumable script

and inside that script there is a while loop
that while loop runs a checkpoint every 250ms, if boolvalue is false then break the while loop

the consumable (in this case being the bandage) is meant to give the player +X health upon finishing the entire while loop, but how can i check if the while loop has finished waiting the 2 seconds successfully (without breaking)

HealEvent.OnServerEvent:Connect(function(player)
	local consumable = player.Character:FindFirstChildOfClass("Tool")
	local humanoid = player.Character.Humanoid
	
	local COOLDOWN = ConsumableStats[consumable.Name]["COOLDOWN"]
	local USE_TIME = ConsumableStats[consumable.Name]["USE_TIME"]
	local using = consumable.Using
	
	if using.Value then player:Kick("Greed is a deadly sin.") return end
	if humanoid.Health == humanoid.MaxHealth then player:Kick("You can always get too healthy.") return end
	
	using.Value = true
	
	while task.wait(USE_TIME) do
		task.wait(COOLDOWN)
		if not using.Value then break end
	end
end)

If I understand correctly, you want to give the player health as long as the code quoted doesnt run.
You can check if it ran by using a variable like this:

local Used = true

while task.wait(USE_TIME) do
	task.wait(COOLDOWN)
	if not using.Value then Used = false break end
end

if Used then
	-- Change the world
end

stupid variable naming by me, but uh

COOLDOWN is essentially a checkpoint, and that checkpoint is meant to well, check every 250ms (in those 2 seconds of USE_TIME) if the value is true, if it isn’t, break the while loop

I’m not sure I quite understand, are you trying to heal the player once per loop as long as using.Value == true?
if so you could just simply put your code after the break as if it breaks then the code after it will not run

nuh uh

i want to heal the player after the loop ends successfully (so if those 2 seconds pass without the loop breaking)

the reason i’m doing a checkpoint every 250ms is to check if using.Value hasn’t been changed (it changes if the player releases LMB)

So if that is the case then the code I wrote above should work.
If using.Value is false (or nil) then the Used variable will be set to false and the loop will break
After that you simply check if Used is true and then you heal the player

the problem with this code being is that using gets set to false whenever the player releases LMB (MouseButton1Up)

Alright I think I get what you mean, in that case you can use a variable to track the amount of time that has elapsed like this:

local TimeElapsed = 0
while task.wait(USE_TIME) do
	task.wait(COOLDOWN)
	if not using.Value then Used = false break end
	TimeElapsed += COOLDOWN
end

if TimeElapsed >= 2 then
	-- Live without regret
end
2 Likes

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