javascript - What to do if the n times in the timer do not increase
曾经蜡笔没有小新
曾经蜡笔没有小新 2017-06-12 09:32:09
0
3
700

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();
    }
}
曾经蜡笔没有小新
曾经蜡笔没有小新

reply all(3)
代言

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);
        });
小葫芦

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);
    }
}
大家讲道理

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!