我的 setTimeout 不能正常工作 [英] my setTimeout doesn't work correctly

查看:62
本文介绍了我的 setTimeout 不能正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码:

var stripeAnimation = function() {

var streetDivWidth = $('.street_name').width();
var streetFull = $('.street_name .street_name_text');

for(var i=0; i<streetFull.length; i++) {
    var item = $(streetFull[i]);
    var widthFull = item.width();
    var remainder = widthFull - streetDivWidth;
    var animationSpeed = widthFull * 5;
    var summary = streetDivWidth - widthFull;
    if(summary < 0) {
        item.children('.gradient_span').addClass('gradient');
        infinite();
        setTimeout(infinite, 1000);
    }

}
function infinite() {
    item.animate({
        marginLeft: '-' + remainder + 'px'
    }, animationSpeed).animate({
            marginLeft: 0
        }, widthFull).delay(1000);
}

}
$(document).ready(function() {
    stripeAnimation();
});

看起来它应该在 1000 毫秒的延迟内一遍又一遍地循环动画 - setTimeout(infinite, 1000);".但事实并非如此.请帮忙!

It looks like it should loop the animation over and over in a delay of 1000ms - "setTimeout(infinite, 1000);". but it doesn't. Please help!

推荐答案

setTimeout 只会调用您的函数一次,但正如 Arun P 所说,您可以选择使用 setInterval,只是不推荐用于动画.setInterval 的问题在于,您指定的延迟间隔是调用它之前的最短时间,而不是在该间隔结束时调用它的承诺.

setTimeout will call your function only once but, as Arun P said, you have the choice of using setInterval, only it isn't recommended for animation. The problem with setInterval is that the delay interval you specify is the minimum time until it will be called but not a promise it will be called when that interval is over.

一个例子是,如果你设置了 300 毫秒的间隔,但队列被其他操作(UI 或其他 JS 操作)阻塞了,比如说,600 毫秒你的函数将被调用两次,一个接一个没有延迟,这将使您的动画不均匀.您无法确保在您的时间间隔内调用超时,只能不小于该时间间隔.

An example will be, if you set an interval of 300 milliseconds but the queue was held up by other operations (UI or other JS operations) for, let's say, 600 milliseconds your function will be called twice, one after the other with no delay, which will make your animation uneven. You can't ensure a timeout will be called at exactly your interval, only no less than that interval.

更好的方法是使用 setTimeout 进行第一次初始调用,就像您所做的那样,然后在 infinite() 函数调用的末尾再次调用 setTimeout(infinite, 1000) 再次.

A better approach would be to make your first initial call with a setTimeout, as you have done, and again at the end of the infinite() function call setTimeout(infinite, 1000) again.

综上所述,如果适用,制作动画的最佳方法是 requestAnimationFrame 方法,您可以在此处查看:

With all that said, if it's applicable, the best way to do animations is the requestAnimationFrame method, you can look into it here:

https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame

这篇关于我的 setTimeout 不能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆