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

查看:115
本文介绍了我的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();
});

看起来它应该以1000ms的延迟一遍又一遍地循环播放动画-"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/zh- US/docs/Web/API/window.requestAnimationFrame

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

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