search

Home  >  Q&A  >  body text

javascript - What to do if the n times in the timer do not increase

I don’t know why the n times in it do not increase, and how to clear the execution after executing it three times.

var firstShow = 1000;
var secondShow = 5000;
var threeShow = 10000;

setTimeout(openMpM, firstShow);
function openMpM() {
    $("#swtCenter2").fadeIn(1000);
}

var n = 0;
function closeM(n) {
    $("#swtCenter2").fadeOut(1000);
    setTimeout(openMpM, 50000);
    n = n++;
    if (n == 1) {
        setTimeout(openMpM, secondShow);
    }
    if (n == 2) {
        setTimeout(openMpM, threeShow);
    }
    if (n == 3) {
        clearTimeout();
    }
}
曾经蜡笔没有小新曾经蜡笔没有小新2788 days ago779

reply all(3)I'll reply

  • 代言

    代言2017-06-12 09:34:09

    In the binding event, first n++ and then execute closeM(n). The n=n++ in closeM(n) must be removed.

        $("#swtCenter2").on('click',function(){
                n=n+1
                closeM(n)
            });

    For the third time, just if (n==3) {$("#swtCenter2").fadeOut(1000);} will do
    or this

            var n=0;
            function closeM() {
            $("#swtCenter2").fadeOut(1000);
            n=n+1;
            return function (n){
                console.log(n)
                if(n==1){setTimeout(openMpM,secondShow);
                }
                if(n==2){setTimeout(openMpM,threeShow);
                }
                if(n==3){$("#swtCenter2").fadeOut(1000);}}
            }
            $("#swtCenter2").on('click',function(){
                closeM()(n);
            });

    reply
    0
  • 高洛峰

    高洛峰2017-06-12 09:34:09

    In fact, your idea is basically very clear, but the details are still a little unclear. For example, setTimeout(openMpM, 50000); This sentence will be executed every time closeM(), regardless of the n value.

    Also n = n++ does not change the n value, it is equivalent to

    var t = n;
    n++;
    n = t;

    The following is my modified code. This question is the same as the one you asked, so I won’t answer it there.

    var firstShow = 1000;
    var secondShow = 5000;
    var threeShow = 10000;
    
    // 定义成数组,便于按序号取用
    var showTimes = [firstShow, secondShow, threeShow];
    
    setTimeout(openMpM, firstShow);
    function openMpM() {
        $("#swtCenter2").fadeIn(1000);
    }
    
    var n = 0;
    function closeM(n) {
        $("#swtCenter2").fadeOut(1000);
    
        // 取出需要等待的时间,并 n + 1
        // 你用的 n = n++ 实际并不会改变 n 值
        var time = showTimes[n++];
    
        if (!time) {
            // 未取到 time 值,说明 3 个时间已用完
            // 重置 n 并且不再延时打开
            n = 0;
        } else {
            setTimeout(openMpM, time);
        }
    }

    reply
    0
  • 大家讲道理

    大家讲道理2017-06-12 09:34:09

    n = n++;
    Due to n operator precedence, n has not changed
    so it should be directly ++n;

    reply
    0
  • Cancelreply