[Help] Script freezing game [SOLVED]

So i spent ages making this script to work as a toggle feature

RegisterNUICallback( "ButtonClick", function( data, cb ) 
	if ( data == "handsup" ) then 
		CancelEvent()
		TriggerEvent("Handsup", source)
	elseif ( data == "rollwindow" ) then
		TriggerEvent("RollWindow", source)
	elseif ( data == "trunk" ) then
		TriggerEvent("Trunk", source)
	elseif ( data == "ragdoll" ) then
		CancelEvent()
		TriggerEvent("Ragtog", source)
	elseif ( data == "doors" ) then
		TriggerEvent("Doors", source)
	elseif ( data == "surrender" ) then 
		TriggerEvent("KneelHU", source)
	elseif ( data == "engine" ) then 
		TriggerEvent("Engine", source)
	elseif ( data == "exit" ) then 
		-- We toggle the ActionMenu and return here, otherwise the function 
		-- call below would be executed too, which would just open the menu again 
		ToggleActionMenu()
		return 
	end 

	-- This will only be called if any button other than the exit button is pressed
	-- ToggleActionMenu()
end )



local ragtog = true
AddEventHandler("Ragtog", function()
	if ( ragtog ) then
		TriggerEvent("Ragdoll", source)
		ragtog = false
	else
		Citizen.Wait(100)
	end
end)

local ragdoll = true
AddEventHandler( "Ragdoll", function()
	while ( ragdoll ) do
		Citizen.Wait(0)
		SetPedToRagdoll(GetPlayerPed(-1), 1000, 1000, 0, 0, 0, 0)
		if ( ragdoll ) then
			RegisterNUICallback( "ButtonClick", function( data, cb ) 
				if ( data == "ragdoll" ) then 
					ragdoll = false
					CancelEvent()
					TriggerEvent("Ragdoll", source)
				end
			end)
		else
			RegisterNUICallback( "ButtonClick", function( data, cb ) 
				if ( data == "ragdoll" ) then 
					ragdoll = true
					CancelEvent()
					TriggerEvent("Ragdoll", source)
				end
			end)
		end
	end
end )

And it works, but after toggling it like 2 times, every time you toggle the script, the game freezes for 2 seconds, toggle it a couple more times, and the game Freezes for 30 seconds, another and the game just stops responding. If I put Citizen.Wait(Anything above 0) the ped looks like hes having a seizure when hes rag dolled, and the game STILL freezes. Does anyone know the answer to this?
I’d really appreciate some help,
thanks for reading

SOLUTION!

--[[ RAGDOLL SCRIPT ]]--
local ragdoll = false
function setPlayerRagdoll(flag)
  ragdoll = flag
end
Citizen.CreateThread(function()
  while true do
    Citizen.Wait(0)
    if ragdoll then
      SetPedToRagdoll(GetPlayerPed(-1), 1000, 1000, 0, 0, 0, 0)
    end
  end
end)

ragdol = true
AddEventHandler("Ragdoll", function()
	if ( ragdol ) then
		setPlayerRagdoll(true)
		ragdol = false
	else
		setPlayerRagdoll(false)
		ragdol = true
	end
end)

You’re using a while loop without creating a separate thread for it.

Wrap the while loop in something like this:

Citizen.CreateThread(function()
  -- while loop here
end)
1 Like

I should probably remove this thread, I fixed it, thanks for the response nonetheless.