某些单词返回后退出调用setInterval()函数的时间

问题描述 投票:0回答:1

我有一个数组,该数组包含的元素我希望在setInterval函数中调用包含在数组中的元素,并且当发生这种情况时,如果其中包含单词,则该数组中的随机元素将在指定的时间开始出现在控制台上匹配的数组本身调用ClearInterval函数。

function shuffle(array) {
      let currentIndex = array.length, temporaryValue, randomIndex;

          // While there remain elements to shuffle...
            while (0 !== currentIndex) {

        // Pick a remaining element...
              randomIndex = Math.floor(Math.random() * currentIndex);
               currentIndex -= 1;

                // And swap it with the current element.
                   temporaryValue = array[currentIndex];
                array[currentIndex] = array[randomIndex];
               array[randomIndex] = temporaryValue;
              }

                return array;
             }


                     let d = ["d","e","a","d"];


                          let c = setInterval(function(){


                 let r = shuffle(d).join("");

             if(r === "dead"){
                   clearInterval(d)
           }else{
               console.log(shuffle(d).join(""))
            }
           },1000)
javascript dom
1个回答
1
投票

通过更改clearInterval(c)尝试此操作

function shuffle(array) {
    let currentIndex = array.length,
        temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
}


let d = ["d", "e", "a", "d"];
let c = setInterval(function() {
    let r = shuffle(d).join("");
    console.log(r)

    if (r === "dead") {
        clearInterval(c) // this should stop here
    } else {
        console.log(shuffle(d).join(""))
    }
}, 1000)
© www.soinside.com 2019 - 2024. All rights reserved.