gpt4 book ai didi

javascript - 某个单词返回后退出计时,调用setInterval()函数

转载 作者:行者123 更新时间:2023-12-02 21:33:39 24 4
gpt4 key购买 nike

我有一个数组,该数组包含我希望在 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)

最佳答案

通过更改 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)

关于javascript - 某个单词返回后退出计时,调用setInterval()函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60560567/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com