javascriptiscroll

Resetting autoscroll intervals with Iscroll


I'm trying to build a page with a carousel using iScrolljs. The position of the carousel should follow the position I'm at in a video. This isn't really relevant to the question but I figured I should give as much information as possible.

The autoscrolling works but I also want the user to have the possibility to scroll themselves. The problem is that when you scroll now every time the interval is called the carousel scrolls to the previous position. I'm trying to work with clearing intervals and resetting them but it doesn't seem to work. This is what I have:

    video.onplay = function(){
myScroll = new IScroll('#carWrapper',{
                scrollX: true,
                scrollY: false,
                momentum: false,
                click:true,
                mouseWheel:true,
                tap: true,
                keyBindings: true
            });

scroll();
    };

    function checkMoved(){
if(document.getElementById('carWrapper')){
        if(!scroller.moved){
                var scrollPos = (video.currentTime/video.duration)*4800;
                myScroll.scrollTo(-scrollPos,0,1000,IScroll.utils.ease.elastic);
        }
    }

if(myScroll.moved){
    clearInterval(scrollInterval);
    myScroll.moved = false;
    setTimeout(scroll(),10000);
}
    }

   function scroll(){
scrollInterval = setInterval(checkMoved,5000);
   }

Thanks in advance!


Solution

  • I changed the code a little bit and got it working.

        video.onplay = function(){
    myScroll = new IScroll('#carWrapper',{
                    scrollX: true,
                    scrollY: false,
                    momentum: false,
                    click:true,
                    mouseWheel:true,
                    tap: true,
                    keyBindings: true
                });
    
    scrollInterval = setInterval(function(){
        if(myScroll.moved){
            resetInterval();
            myScroll.moved = false;
        }
        else if(document.getElementById('carWrapper')){
            if(!scroller.moved){
                    var scrollPos = (video.currentTime/video.duration)*4800;
                    myScroll.scrollTo(-scrollPos,0,1000,IScroll.utils.ease.elastic);
            }
        }
    },5000);
       };
    
        function resetInterval(){
    clearInterval(scrollInterval);
    scrollTimeout = setTimeout(function(){
        scrollInterval = setInterval(function(){
            if(myScroll.moved){
                resetInterval();
                myScroll.moved = false;
            }
            else if(document.getElementById('carWrapper')){
                if(!scroller.moved){
                    var scrollPos = (video.currentTime/video.duration)*4800;
                    myScroll.scrollTo(-scrollPos,0,1000,IScroll.utils.ease.elastic);
                }
            }
        },5000);
    },10000);
        }
    

    It's probably not the cleanest code but I'm happy it works.