Search code examples
javascripttimeout

JS : Set Timeout not working with Child Element count


I was wondering what this mysterious output in the chrome dev console is when I run a timeout with a childElementCount and it seems to increment by one each time I re-run the function.

function Eggs(){
var f = document.getElementById("x").childElementCount;
console.log(f);
}
setTimeout(Eggs(), 3000);
/* output should be:
0
8
in the chrome console */
<!DOCTYPE html>
<html>

<body>
    <div>
        <div>
            <div id="x"></div>
        </div>
    </div>
</body>

</html>

it works just fine and gives me the correct number of children


Solution

  • Try like next:

    let eggs = function () {
        let el = document.getElementById('x');
        console.log(el.childElementCount);
    };
    
    setTimeout(eggs, 3000);
    

    Names of functions MUST be in camelCase!

    The eggs variable store the function, but eggs() - gives to us the result of calling it (what you would have in function return).

    let eggs = function () {
        return function () {
            let el = document.getElementById('x');
            console.log(el.childElementCount);
        };
    };
    
    setTimeout(eggs(), 3000);