What method Instance:WaitForChild uses to check for an child with given name? If it uses loops, what is the time to elapse since every check?

The question is, what is the method Instance:WaitForChild uses to check for an child with given name? Does it detect .ChildAdded events on the instance and check if that added child name’s is the given parameter or it uses loops? If it does use loops, what is the elapsed time for every check?

Is there also any other way it uses to check for that child?

C++ codes?

ChildAdded is an event, with a function provided, where its only parameter is the name of the instance that’s added into that instance.

I’m afraid you wasn’t very helpful, and what’s the matter with explaining Instance.ChildAdded? Also, I couldn’t even understand that well.

What do you mean? It’s an event of an instance.

There isn’t logic in your code your basically scanning for names and ChildAdded is also a event like zues said. Your code doesn’t make sense there is 0 logic.

I believe WaitForChild is coded somewhat like this:

local RS = game:GetService("RunService")
function Instance:WaitForChild(ChildName, Timeout)
  assert(ChildName == "string", "error message here")
  local T1 = os.time()
  repeat RS.Heartbeat:Wait() until self[ChildName] or os.time - T1 >= Timout or 10
  return self[ChildName]
end

It’s probably not very accurate but it’s the idea; self is referring to the Instance you’re calling WaitForchild on’s metatable.


Read more about it here.

2 Likes

Are you talking to me? My code is 0 logic?

No, I was referring to the topic creator! My apologies. :slightly_smiling_face:

1 Like

I don’t find how the code can make 0 logic. Here’s an representation of it:


function WaitForChild(childName, timeOut) -- Assuming self is the instance where it was called, just like TopCrundee stated.
    -- Option 1:
    local Child
    Child = self:FindFirstChild(childName)
    if Child then 
        return Child
    end

    self.ChildAdded:Connect(function(childAdded)
        if childAdded.Name == childName then
            Child = childAdded
        end
    end)

    -- Option 2:

    local Child
    repeat game:GetService('RunService').Heartbeat:Wait()
    Child = self:FindFirstChild(childName)
    until Child    
end

Note: This a super simplified version of what I suppose.

Now, the thing is, if it does use loops, what is the elapsed time between every check? In this simplified version, the elapsed time / yield is set to when RunService.Heartbeat is fired.

Edit: Let’s suppose there is a repeat loop below Option 1, which stops until Child is not nil. And returns child once it meets the condition.