jsFiddle demo
The answer actually lies in the use of variable scope. The variable i
only exists for the scope of the setInterval
callback function. Before and after that function the variable doesn't exist, so it can't hold a value… it just gets re-initialized every time the function starts. If we move the variable outside of the setTimeout
function, it becomes part of a larger scope, that of the $(document).ready
event handler. It will remain available for both that scope and all other scopes inside of that scope (in this case, the setTimeout
callback).
A good book to read about Javascript is Douglas Crockford's Javascript: The Good Parts. There's also a good post explaining scope and closures at How do JavaScript closures work?