0

How can I add to last number +1, every time document does interval? I'm getting this: jsfiddle.net/zAt7C/1/

$(document).ready(function () {
    // verification
    $('title').text('jQuery is working!');

    // loop
    setInterval(function () {
        for (var i = 1; i < 2; i++) {
            $('.repeat').append(i + ' ');
        };
    }, 1000);
});
Igor
  • 33,276
  • 14
  • 79
  • 112
  • What does blankblaNk mean.? The general idea is that one would use all the space in the question box to post code. While the jsfiddle is helpful, you should also include your code here, in case the link breaks, amd so folks dont have to leave stack overflow. If this gets closed, you can still edit your post to get it reopened. Good luck! :-) – jamesmortensen Mar 28 '13 at 01:55

3 Answers3

0

LIVE DEMO

var i = 0;
setInterval(function () {
    $('.repeat').append(' '+ (i++) );
}, 1000);
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
0

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?

Community
  • 1
  • 1
thirdender
  • 3,891
  • 2
  • 30
  • 33
0
$(document).ready(function () {
    // verification
    $('title').text('jQuery is working!');

    (function func (i) {
        setTimeout(function () {
            $('.repeat').append(i + ' ');
            i += 1;

            if (i <= 10) {
                func(i);
            }
        }, 1000);
    }(0))
});

Fiddle

pdoherty926
  • 9,895
  • 4
  • 37
  • 68