Running a script before its detroyed

Hi everyone. I am trying to create a pet food system. I have an updating inventory system that has buttons to gives the pet food. But if a player presses a button just as the inventory is being reloaded the script runs about 50% and gets stuck. An example: (You can see on the second try it gets stuck after tweening) robloxapp-20210628-1336361

The script in the button:

local function onClick()	
	local food = script.Parent.Parent.Parent.Parent.Back.Pet.Pet.Food
	
	food.Image = script.Parent.ImageLabel.Image
	food.Position =UDim2.new(0.553, 0,0.53, 0)
	
	wait()
	
	food.Visible = true
	
	local TweenService = game:GetService("TweenService")
	
	local Tween = TweenService:Create(food, TweenInfo.new(0.5), {Position = UDim2.new(0.439, 0, 0.349, 0)})	
	
	Tween:Play()
	
	local numberVal = script.Parent.Name
	
	wait(0.5)
	
	food.Visible = false
	
	script.Parent.Sound:Play()
	
	local stat = game.Players.LocalPlayer.PetFood:FindFirstChild(numberVal)
	
	if stat.Value > 0 then
		game.ReplicatedStorage.Money.RemoveFood:FireServer(numberVal)
	end
end
	
script.Parent.MouseButton1Click:Connect(onClick)

You could try Tween.Completed instead of wait(0.5)

This hasn’t helped to fix the issue

What do you mean by “just as the inventory is being reloaded”?

You can try use spawn(function() or corountine.wrap(function()

Try maybe this:

local function onClick()	
	local food = script.Parent.Parent.Parent.Parent.Back.Pet.Pet.Food

	food.Image = script.Parent.ImageLabel.Image
	food.Position =UDim2.new(0.553, 0,0.53, 0)

	wait()

	food.Visible = true

	local TweenService = game:GetService("TweenService")

	local Tween = TweenService:Create(food, TweenInfo.new(0.5), {Position = UDim2.new(0.439, 0, 0.349, 0)})	

	Tween:Play()

	local numberVal = script.Parent.Name
	
	spawn(function()
		wait(0.5)

		food.Visible = false

		script.Parent.Sound:Play()

		local stat = game.Players.LocalPlayer.PetFood:FindFirstChild(numberVal)

		if stat.Value > 0 then
			game.ReplicatedStorage.Money.RemoveFood:FireServer(numberVal)
		end
	end)
end

script.Parent.MouseButton1Click:Connect(onClick)

Issue was fixed. I made the inventory only load when the player opens the gui.