How can a While True loop be converted into a Runservice.Hearbeat Loop?

This script contains task.waits so I haven’t been able to convert it easily.

local HeatedItems: Folder = plr:WaitForChild("HeatedItems")
    local FurnaceCollectables: Folder = plr:WaitForChild("FurnaceCollectables")
    local queue = {}
    local meta = {}
    local currentBar = plr:WaitForChild("CurrentBar")
    setmetatable(queue, meta)
    meta.__index = function(tabl, key)
        print(key.." not found!")
    end
    local burnItemFurnace: RBXScriptConnection = nil
    HeatedItems.ChildAdded:Connect(function(child)
        print(queue)
        table.insert(queue, child)
    end)
    local n = plr.Name
    local furnaceevents: RBXScriptSignal = nil
    local count = 0 
    local cooldown = false
    while true do
        if game:GetService("Players"):FindFirstChild(n) == nil then
            return
        end
        if #HeatedItems:GetChildren() ~= 0 and checkFurnanceCount() >=1 then
            local firstqueue: IntValue = queue[1]
            local timedivided = inventoryModule[firstqueue.Name].Meltable[2]/100
            for i=1, 100, 1 do
                task.wait(timedivided)
                currentBar.Value +=1
            end
            table.remove(queue, 1)
            if not FurnaceCollectables:FindFirstChild(firstqueue.Name) then
                local productValue = Instance.new("IntValue")
                productValue.Name = firstqueue.Name -- got nil for product
                productValue.Parent = FurnaceCollectables
            end
            FurnaceCollectables[firstqueue.Name].Value +=1
            productEvent:FireClient(plr, firstqueue.Name)
            HeatedItems:FindFirstChild(firstqueue.Name):Destroy()
        end
        task.wait(1)
    end```
1 Like

you could make a debounce inside of the heartbeat so it only runs once the debounce is up.

local debounce = false

game["Run Service"].Heartbeat:Connect(function()
    if debounce then
        return
    end

    debounce = true

    --stuff here, like waiting

    debounce = false
end

also i suggest postSimulation over heartbeat. i think they are currently identical but heartbeat may be deprecated in the future(?) since it looks like roblox is renaming (and probably optimizing) a ton of these connections.

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