在不完成当前循环的情况下立即停止setTimeout循环

Immediately stop a setTimeout loop without finishing current cycle

本文关键字:循环 setTimeout 情况下      更新时间:2023-09-26

Im正在创建一个用户操作的随机选择器。用户点击一个按钮,系统会随机选择两个结果(将是视频)。

然后,页面将交替突出显示两个随机结果——用户可以再次点击按钮,然后选择他们想要的视频。

这一切都运行得很好,但交替高亮显示是通过setTimeout循环完成的,该循环结束了当前周期,而不是立即停止。

我该如何获得它,以便当用户按下"选择"按钮时,flit函数立即停止——而不是当当前循环结束时?

这是小提琴

http://jsfiddle.net/zandergrin/tmwst5z9/4/

ps-抱歉,但这是一项正在进行的工作-我知道这里有一些混乱的地方。。。var区间=0;

function random() {
    // create the array
    var posts = ["post 1", "post 2", "post 3", "post 4", "post 5", "post 6", "post 7", "post 8", "post 9", "post 10"];
    var results = posts
    // Shuffle array
    .sort(function () {
        return .5 - Math.random()
    })
    // Get first 2 items
    .slice(0, 2);
    var post1 = results[0];
    var post2 = results[1];
    // add them to the DOM
    $('#res1').html(post1);
    $('#res2').html(post2);
    // loop it
    interval = setTimeout(random, 100);
}
function start() {
    // Hide the start button
    $("#start").css("display", "none");
    $("#stop").css("display", "block");
    // Start the randomizer
    random();
}

function stop() {
    // Hide the stop button and stop the random() timeout
    clearTimeout(interval);
    $("#stop").css("display", "none");
    $("#select").css("display", "block");
    // set the inital background colour
    $("#res1").css({'background': '#123','color': '#fff'});
    $("#res2").css({'background': '#eee','color': '#000'});
    //create a function to flick between items
    function flit() {
        //color the results
        setTimeout(function () {
            $("#res1").css({'background': '#eee','color': '#000'});
            $("#res2").css({'background': '#123','color': '#fff'});
        }, 800);
        //colour again after a delay
        setTimeout(function () {
            $("#res1").css({'background': '#123','color': '#fff'});
            $("#res2").css({'background': '#eee','color': '#000'});
        }, 1600);
        //loop it
        timer = setTimeout(arguments.callee, 1600);
    };
    //run the flick function
    flit();
}

function select() {
    // stop thie flit function - doesnt stop immediately!
    clearTimeout(timer);
    $("#select").css("display","none");
    $("#refresh").css("display", "block");
}
function refresh() {
    location.reload();
}

问题出在flit()函数中——您需要为setTimeout调用分配引用,以便对它们调用clearTimeout。现在,您正在阻止在select()方法中调用flit(),但这两个计时器仍在排队等待将来执行。

除了@sholanozie答案,我建议将这些setTimeout放在一个数组中(即arrayOfTimeouts),然后:

function select() {
    // stop thie flit function - doesnt stop immediately!
    arrayOfTimeouts.forEach(function(setTimer) {
        clearTimeout(setTimer);
});