javascriptjquerysetinterval

setInterval function not always working as intended


So, I tried to do an animated banner (containing two images- #baner1 and #baner2. When one fades out the second fades in). It works properly most of the times, but sometimes these images change rapidly (like one second after each other, despite the timer is 12000 miliseconds). Any idea what causes it?

My code:

setInterval(()=>{
  $('#baner1').fadeOut(2000);
  $('#baner2').fadeIn(2000);
},12000)

setInterval(()=>{
  $('#baner1').fadeIn(2000);
  $('#baner2').fadeOut(2000);
},24000)

Also, it's (as far as I know) my only code affecting these images. Thanks in advance for help.


Solution

  • Your callbacks are overlapped.

    They go like a, a+b, a, a+b...

    The a+b is sometimes executed as b+a (because two setIntervals aren't synchronized perfectly) and I think this is what's causing you trouble.

    What you meant to do is a, b, a, b...

    You can try changing you logic to use a single setInterval, and use a variable to know if it's the a "turn" or the b "turn". Something like this:

    let nextTurn = 'a';
    setInterval(()=>{
        if (nextTurn === 'a') {
            $('#baner1').fadeOut(2000);
            $('#baner2').fadeIn(2000);
            nextTurn = 'b';
        } else {
            $('#baner1').fadeIn(2000);
            $('#baner2').fadeOut(2000);
            nextTurn = 'a';
        }
    },12000)