简体   繁体   中英

using requestAnimationFrame with wait time

I've some basic script to scroll a text to the right and left which I tried to convert it from timeout to requestAnimationFrame , however, I can't make it work.

function slideHorizontal(e, amount, time) {

    var waitTime = 500;

    e.animate({
        marginRight: '-'+amount+'px'
    }, time, 'linear', function() {
        setTimeout(function() {
            e.animate({
                marginRight: 0
            }, time , 'linear', function() {
                setTimeout(function() {
                    slideHorizontal(e, amount, time);
                }, waitTime);
            });
        }, waitTime);
    });

}

any suggestion how I can apply the wait time with requestFrameAnimation ? BTW, should I even use jQuery.animate() if I'm going to use the requestFrameAnimation ?

No, requestAnimationFrame() does not make any sense when you use jQuery's animate() . jQuery may use requestAnimationFrame() internally though.

You can use requestAnimationFrame() to replace setTimeout() when you run the main animation loop with setTimeout(f, x) . Instead of having a animation frame every x ms, requestAnimationFrame() lets the browser control the frame rate. The actual rate will then be based on whatever the browser deems necessary for a smooth animation, depending on the hardware and other factors. The browser can also lower the refresh rate when the window/tab is not visible, to conserve CPU time and reduce power usage of animations that are not visible.

But that's not what you are using setTimeout() for. You use it to wait between two animations. There are more elegant ways of doing this , but requestAnimationFrame() isn't one of them.

here's how you would use requestAnimationFrame :

 var i = 0; var forward = true; function draw() { requestAnimationFrame(draw); if(i < 100 && forward){ i+=2; } else if(i > 0){ forward = false; i-=2; } else{i = 0; forward = true;} document.getElementById("div").style.left = i + "px"; } draw(); 
 div { width: 80px; height: 80px; background: black; position: absolute; } 
 <div id="div"></div> 

The setInterval equivalent would be:

 var i = 0; var forward = true; function draw() { setInterval(function(){ if(i < 100 && forward){ i+=2; } else if(i > 0){ forward = false; i-=2; } else{i = 0; forward = true;} document.getElementById("div").style.left = i + "px";},10); } draw(); 
 div { width: 80px; height: 80px; background: black; position: absolute; } 
 <div id="div" onload="draw"></div> 

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