Hi, im new about a scripting in fivem or other scripting files, so i want to ask about how to stop a loop client-side event like this?
stressrd:onPlayerInOut(function(isPointInside)
if isPointInside then
while true do
TriggerServerEvent('hud:server:RelieveStress', math.random(2, 5))
end
else
break
end
end)
I already make event that if player going inside the zone "isPointInside " will loop a event “hud:server:RelieveStress” and then when going out of the zone it will break or stop the loop.
But the loop still running.
Thanks
The reason the loop is never breaking, is because you have a while true do loop and true is, well, always true. So it never gets broken. You may call this event when leaving the zone, passing isPointInside as false, but that will try to break a loop that it’s not inside of. Break works INSIDE a loop, but here it’s outside. Here is what you can do.
local isPointInside = false
stressrd:onPlayerInOut(function(isInside)
if isInside and not isPointInside then
isPointInside = true
CreateThread(function()
while isPointInside do
TriggerServerEvent('hud:server:RelieveStress', math.random(2, 5))
Wait(1000) -- Time in ms between stress relief ticks
end
end)
else
isPointInside = isInside
end
end)
Here is what we did.
Create a variable isPointInside OUTSIDE the scope of the function that defaults as false. The function receives a different named variable (isInside) and IF isInside is true AND the loop is not currently running (not isPointInside), then it sets isPointInside to true and starts looping. This prevents the loop running multiple times, at the same time, lowering stress faster than intended. It also got put inside a thread to allow the rest of your code to continue and not wait for this to return once the loop is broken. Now, if you pass a false value to this function, it avoids creating the thread and loop and sets isPointInside to false. This will break the loop that was creating on the call that passed a true value. Give that a crack and if it works, mark this post as the solution so others can learn too! Good luck!
Nice! Thanks for your help and the advice, and it’s working!!, but don’t forget about the Citizen.Wait(1000) inside the code, becuase it’s make me crash every inside the zone haha
Ah yes, I forgot about the required wait, because I used your code as a starting point and didn’t pick up on it’s absence. I have adjusted the solution so others don’t copy and paste it for their purposes and have the same issue. Thanks, mate!