在javascript或jquery中延迟就绪函数()

Nic*_*Div 1 javascript jquery

//this code animates the divs to the left after every 5 secs
$(document).ready(function() {

    var refreshId = setInterval(function() {
        $('.box').each(function() {
            if ($(this).offset().left < 0) {
                $(this).css("left", "150%");
            } else if ($(this).offset().left > $('#container').width()) {
                $(this).animate({
                    left: '50%'
                }, 500);
            } else {
                $(this).animate({
                    left: '-150%'
                }, 500);
            }
        });
    }, 5000);)
};?
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,每当页面被加载时,div元素每隔5秒就会保持滑动.但是我的网页上有一个按钮,当点击时,div根据点击的按钮分别向左或向右移动元素.但问题是在buuton点击时有时会重叠的自动动画和动画.因此,每当我点击按钮时,我想再次将自动动画延迟document.ready5秒.

这显示在这个jsFiddle中.当您继续单击"左侧动画"​​或"右侧动画"按钮时,div有时会重叠.所以我只想在点击按钮时延迟自动动画.

Jam*_*arp 6

您可以调用clearInterval(refreshId),然后重新运行代码以设置旋转.

这是一个如何做到这一点的草图.我担心我可能无法提供比这更详细的信息,但我希望它有所帮助!

$(document).ready(function () {
    var refreshId;
    function startRotation() {
        refreshId = setInterval(function () { /* rotate stuff */ }, 5000);
    }
    function restartRotation() {
        clearInterval(refreshId);
        startRotation();
    }
    startRotation();

    var button = /* find the buttons that should restart the rotation */;
    button.click(restartRotation);
};
Run Code Online (Sandbox Code Playgroud)