0

I have a jquery function, first(), which I have running on page load to do a carousel of images. When the user scrolls down, I want the function to pause - and ideally, but not necessarily - to resume when you scroll back to the top of the page.

I've tried various things, including:

$(document).ready(function first(){
etc
});


$(window).scroll(function(){    
if ($(window).scrollTop()==0){
first()
}
else {
second() 
}
});

Where second() just displays one image (call it A) in the carousel. But that just inserts image A into the sequence until the next carousel transition - presumably because I have first() running from page load and it's not stopping. How can I pause it? Thanks!

JohnG
  • 486
  • 3
  • 22

1 Answers1

0

the best solution that I could think of is to use the date objects to essentially pause the function for n seconds. I hope this helps

https://jsfiddle.net/8r87en6t/1/

var counter = $('#count'),
    pause = new Date();

//function to run continuously
function increment() {
    var now = new Date();
    setTimeout(function () {
        if (now > pause) {
            var current = parseInt(counter.text());
            counter.text(current += 1);
        }
        increment();
    }, 100);
};

//kick it off intially
increment();

//scroll watch
$(document).on('scroll', function () {
    pause = new Date();
    pause.setSeconds(new Date().getSeconds() + 2);
});
stackoverfloweth
  • 6,669
  • 5
  • 38
  • 69