简体   繁体   中英

Why isn't this scroll-animate working?

Here's a fiddle--- http://jsfiddle.net/mFrbA/2/

Which is just a test for the code below. I'm trying to get it to scroll down all the way, slowly and steadily. The reason I'm not just executing it the straightforward way, by scrolling straight to the bottom of the document, is because I want to do it in increments while giving the user a chance to cancel it (hence the variable scrolling , which can be toggled by an outside function.

The reason for the wait variable is to (theoretically) prevent the while loop from looping faster than the animation-- I wasn't sure if it would wait for the animation to finish before starting over. But the complete function is never getting called, and the animation is never happening in the first place.

However, none of this is executing. I'm not sure what I'm doing wrong.

$(function() {
    scrolling = true;
    while (scrolling) {
        var wait = true; 
        $('html, body').animate(
            { scrollTop: '+=50' }, 
            { duration: 800,
             easing: 'linear',
             complete: function(){
                 alert("hi again");
                 wait = false;}
            }
        );
        while(wait) {
            console.log("waiting");
        }
    }
});

JavaScript in browsers is single-threaded (in practice) with an event loop. Your while(wait) ties up JavaScript execution, so the animation (which is asynchronous) never has a chance to happen.

This is why we have callbacks, and there's pretty much no working around that, except with a horrible setInterval thing.

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