0

I am logging a variable to the console as I move through a for loop, but I would like it to occur at intervals, so I am trying to use setTimeout.

function foo(val) {
    return function() {
        setTimeout(function() {
            console.log(val);
        }, 2000);
    };
};

$(function() {
    for (var i = 1; i < 15; i++) {
        $(foo(i));
    };
});

The first instance works properly (it occurs after 2000 milliseconds), but the remaining iterations log the variable immediately. They don't have their own delays. What am I doing wrong?

Chris
  • 3
  • 2
  • What is `$(foo(i));` – Tushar Jul 10 '15 at 04:53
  • http://jsfiddle.net/arunpjohny/hboxdsb1/1/ – Arun P Johny Jul 10 '15 at 04:56
  • Okay, I've looked at the question that is a duplicate of mine. While I see that I can make it work by adding to the delay each time through the loop, I don't understand why I need to. Why does each loop execute at once without the delay each time? I also looked at your fiddle, which does not work for me, until I add the JQuery $ ready method, which you said was unnecessary. I see that it's unnecessary, but it doesn't work for me without it. Sooo confused.... – Chris Jul 11 '15 at 01:48

0 Answers0