0

对于我的一生,我无法弄清楚如何清除数组中的超时(如果存在)。

我有一个单页应用程序(SPA)网站(http://www.rock3t.ca/),每次单击“主页”时 ID 都会增长得非常快,这似乎并没有取消超时。访问该站点,您会看到中心徽标下方的标语以非常快的速度变化,然后变慢。快速单击“主页”多次以查看它的反应。它还没有清除,你会注意到光点。

//slogans
function loadSlogans(){

    //slogan timeouts
    var sloganTimeouts = [];

    //slogans
    var slogans = ['Websites', 'Apps', 'Media', 'Code', 'SEO', 'CRM','Ads','Flyers','Logos','Games','Streams','Web','Websites', 'Apps', 'Media', 'Code', 'SEO', 'CRM','Ads','Flyers','Logos','Games','Streams','Web'];

    var sloganTime = 100;
    var sloganTimeFade = 0;
    var slogans_length = slogans.length;
    var sloganHalfTime = slogans_length / 2;

    //clear slogan timeouts
    $(slogans).each(function(i){

        //clear timeout if exists
        if(typeof sloganTimeouts[i] !== "undefined"){
          clearTimeout(sloganTimeouts[i]);
        }
    });

    //slogan timeout
    function runSloganTimeout(i) {

        //easing out time when half way
        if(i > sloganHalfTime){
            sloganTimeFade++;
            sloganTime = (i * 100) + (sloganTimeFade * 100) * (sloganTimeFade / 4);
        }else{
            sloganTime = i * 100;
        }

        //set timeouts
        sloganTimeouts[i] = setTimeout(function(){

            //append slogans
            $('#slogan span').html(slogans[i]);

        },sloganTime);
    }

    //each slogan
    $(slogans).each(function(i){

        //run
        runSloganTimeout(i);
    });
}

谢谢

4

1 回答 1

0

它已清除,但前一个过程尚未结束,因此您不会清除所有即将发生的超时。解决方法之一:添加processId全局var,打断之前的进程。看我的例子: Plunker

var processId = 0;

//slogans
function loadSlogans(){

    processId++;

    var selfProcessId = processId;

    //slogan timeouts
    ...
    //slogans
    ...
    //clear slogan timeouts
    ...

    //slogan timeout
    function runSloganTimeout(i) {
        //easing out time when half way
        ...
        //set timeouts
        sloganTimeouts[i] = setTimeout(function(){
            //append slogans
            if( selfProcessId == processId )
                $('#slogan span').html(i+slogans[i]);

        },sloganTime);
    }

    //each slogan
    $(slogans).each(function(i){

        //run
        if( selfProcessId == processId )
            runSloganTimeout(i);
    });
}
于 2017-05-02T04:54:09.810 回答