Function called Multiple Times from While Loops

Hello everyone,

I am trying to make a script that prevents a player from running or jumping after their stamina runs low. However, I found a bug where if you spam the two keys at the same time, the “changeStrength” function will be called multiple times. Therefore, the regeneration meter will run twice as fast (not good)! I believe I need to put in a debounce, but I am not sure where it needs to be. If I put it inside the function “changeStrength”, then the loop will only run one time.

Any help would be greatly appreciated!

function changeStrength()
	strength = strength + .25
end

UIS.InputEnded:connect(function(key)
	if key.KeyCode == Enum.KeyCode.LeftShift and running then
		running = false
		while strength ~= max and not running and not jumping do
			changeStrength() -- function called multiple times
			wait(.1)
		end
	end
	
	if key.KeyCode == Enum.KeyCode.Space then
		jumping = false
		while not running and strength ~= max and not jumping do
			changeStrength() -- function called multiple times
			wait(.1)
		end
	end
end)

Put an extra if statement to prevent the while loop from running again with a separate condition. Set the boolean to the opposite type after the loop has ended.

1 Like