Why not this code loop?

var fadeCounter = 0;

function fadeNext() {
  window.fadeCounter++;
  s = '#slide' + window.fadeCounter;
  $(s).fadeIn(1000,fadeNext);
  //forgive typos above, code works, what doesn't:
  if (window.fadeCounter == 8) window.fadeCounter = 0;
  //code will loop up to 8, then stop. why?
}

//initiate loop
fadeNext();

change

The demo is added at http://jsfiddle.net/AXRBh/2/ In the demo, the loop should reset to 20, but it stops. Why?

+3
source share
6 answers

If fadeCounternot declared in the global scope, this will not work. Make sure you specify the variable outside the handler document.ready(or delete it window.).

The function does call (only once, see the next paragraph), but you do not see the effect . After the first "cycle" all the elements are visible, so the second time the call fadeInhas no effect on them.

, fadeIn , : http://jsfiddle.net/fkling/nZ7Mn/
fadeNext, , , reset:

  // s is already visible, so `fadeNext` is called immediately
  $(s).fadeIn(1000,fadeNext);
  // only after that the timer is reset (too late)
  if (window.fadeCounter == 8) window.fadeCounter = 0;

#slide9, fadeIn , .

@Cybernate, . , . , .

, , . :

var max = 4;

function fadeNext(i) {
  i = i % max;
  $('body').append('<div>Current counter: ' + i + '</div>');
   $('#s' + i).fadeIn(1000,function() {
       $(this).fadeOut(1000, function(){fadeNext(i + 1)});
   });                                      
}

//initiate loop
fadeNext(0);

, ( " ", ), .

DEMO

: ?

+4

reset .

var fadeCounter = 0;

function fadeNext() {
  window.fadeCounter++;
  s = '#slide' + window.fadeCounter;
  if (window.fadeCounter == 8) window.fadeCounter = 0;
  $(s).fadeIn(1000,fadeNext);
  //forgive typos above, code works, what doesn't:

  //code will loop up to 8, then stop. why?
}

//initiate loop
fadeNext();
+3

:

fadeLoop(0);

function fadeLoop(id) {
  if (id <= 8) { // add "&& id >= 0" if you're pedantic
    $("#slide" + id).fadeIn(1000, fadeLoop(id+1));
  }
}
+2

? ?

:

http://jsfiddle.net/AXRBh/

$(document).ready(function() {
    var fadeCounter = 0;
    var time = setInterval(fadeNext, 2000);

    function fadeNext() {
       fadeCounter++;
       $('.slide').fadeOut(1000,function(){
          s = '#slide' + fadeCounter;
          $(s).fadeIn();
       });
       if (fadeCounter == 8)
          fadeCounter = 0;
    }
});
+1

, fadeCounter ( ?). :

//initiate loop
$(document).ready(function(){
   window.fadeCounter = 0;  //Explicitly reference it as  a global var
   fadeNext();
});

fadeNext() .

0

, .

For the ninth time through a loop, your code will try $('#slide9').fadeIn

Script Usage Example

0
source

All Articles