my setTimeout doesn't work correctly

雨燕双飞 提交于 2019-12-11 19:42:32

问题


this is the code:

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();
});

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!


回答1:


If you want to loop, then you need to use setInterval()

setInterval(infinite, 10000);

then

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



回答2:


Remainder variable is local and u are using it as like global function. should declare it globally.




回答3:


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.

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.

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.

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



来源:https://stackoverflow.com/questions/19475595/my-settimeout-doesnt-work-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!