我试图在5秒后停止此JavaScript功能。
以下是代码:
<p id="para"></p>
var niceThings = ["You're cool", "You're smart", "You're good looking", "You're a baus", "You're a cool cat."];
var i =0;
function compliment () {
document.getElementById("para").innerHTML = niceThings[i];
if(i < niceThings.length-1) {
i++;
}
else {
i=0;
}
}
window.onload = setInterval(compliment, 500);
我确定有一种方法可以在某处使用setTimeout方法,但我是一个新手。有什么想法吗?
答案 0 :(得分:3)
setInterval
返回一个令牌,可以在5秒后传递给clearInterval
,以阻止愚蠢的功能。
另请注意,您可以使用模(%
)运算符来简化数组循环逻辑。
var niceThings = [
"You're cool",
"You're smart",
"You're good looking",
"You're a baus",
"You're a cool cat."
]
var p = document.getElementById("para")
var i = 0
function compliment () {
p.textContent = niceThings[i]
i = (i + 1) % niceThings.length
}
setTimeout(clearInterval, 5000,
setInterval(compliment, 500)
)
<p id="para"></p>