logrox
logrox

Reputation: 53

Why this iteration works forever

Why this code run infinite time. I don't understand what happened.

(function(){
    console.log("Start")

    function add(){
        s.delete(add); //When I delete this line, everything works fine.
        s.add(add);
        console.count("run")
    }

    const s = new Set([
        add
    ]);

    s.forEach(value => {
        value()
    });
    
    console.log("Finish")
})()

This is an overview code.

Upvotes: 2

Views: 52

Answers (1)

MinusFour
MinusFour

Reputation: 14423

The answer for this is in the spec for Set.prototype.forEach:

Each value is normally visited only once. However, a value will be revisited if it is deleted after it has been visited and then re-added before the forEach call completes. Values that are deleted after the call to forEach begins and before being visited are not visited unless the value is added again before the forEach call completes. New values added after the call to forEach begins are visited.

Since it's a function that you keep adding and running it keeps doing that, deleting and adding it back again. So therefore you create an infinite loop.

Upvotes: 2

Related Questions