将jquery回调构建到requestAnimationFrame函数中以获取间隔

时间:2015-04-16 23:46:46

标签: jquery css jquery-callback requestanimationframe

在我的函数中,我使用requestAnimationFrame从左到右为div的移动设置动画。

move_right =  function(object){
  movement_right_ID = requestAnimationFrame(function(){
    move_right(object)  
});
    $(object).css({
         left: "+=5"
     })
     get_boundary(object) //this is another function that gives me the div boundaries and returns object_left
     if(object_left > $(window).width()){
         cancelAnimationFrame(movement_right_ID);
         $(object).css({
             left: "-100%"
         })
     }
}

此功能按我的意愿运行,即它将div从左向右平滑移动并将其重置到左侧位置。

我的问题是,我想多次运行整个动画:

当我使用

setInterval(function(){
        move_right($("#div1"))
    }, 1000);

我遇到的问题是它在启动后很快就会运行。我怀疑这是因为想要再次运行时动画没有完成。

我在这里寻找类似回调的解决方案,但不希望切换到animation方法。

那么如何在完成后更改代码以1000ms间隔运行该函数?

1 个答案:

答案 0 :(得分:0)

这对你有用吗?

window.requestAnimFrame = (function () {
    return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback) {
        window.setTimeout(callback, 1000 / 60);
    };
})();

var winWidth=$(window).width();
var myBox=$('.box');
var toggler=$('.toggler');
toggler.on('click',toggle);
myBox.isMoving=false;
myBox.timeoutID=null;
requestAnimFrame(render);

function render(){
    requestAnimFrame(render);
    moveBox();
}

function moveBox(){
    if(myBox.isMoving){
        myBox.css({left:'+=5'});
        if(myBox[0].getBoundingClientRect().left>winWidth){
            myBox.isMoving=false;
            clearTimeout(myBox.timeoutID);
            myBox.timeoutID=setTimeout(function(){myBox.isMoving=true;},1000);
            myBox.css({left:0});
        }
    }
}

function toggle(){
    myBox.isMoving=!myBox.isMoving;
    if(!myBox.isMoving){clearTimeout(myBox.timeoutID);}
}
html, body {
    margin: 0;
    padding: 0;
}
.box {
    position: relative;
    left: 0;
    margin: 10px 0;
    background: #cc0;
    width: 20px;
    height: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="box">&nbsp;</div>
<input class="toggler" type="button" value="Toggle" />