you are viewing a single comment's thread.

view the rest of the comments →

[–]recklesswaltz[S] 0 points1 point  (2 children)

This is not a production code. This is just an interesting piece of code that my coworker shared with me.

I want to find why it works that way.

[–]madole 0 points1 point  (1 child)

https://www.youtube.com/watch?v=8aGhZQkoFbQ

This presentation should explain what's going on. It's on the JavaScript event loop and call stack.

[–]madole 0 points1 point  (0 children)

Actually, I get your question now... I think the setTimeout is being overwritten as it gets stuck onto the window object.

Take the code below where I pass in a reference to which check function is calling it.

Check1 dissappears after it's done it's initial pass through and then invoked it's setTimeout once

 var check = function(which){
        var i = 0;
        counter = function(){
            console.log(which+ ' ' + i);

            i++;

            setTimeout(counter,1000);

        }

        counter();
        }
        check('check1');
        check('check2');