简体   繁体   中英

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.

Your callbacks are overlapped.

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

The a+b is sometimes executed as b+a (because two setInterval s 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM