gpt4 book ai didi

javascript - 如何让这个javascript数组值循环并停在最后一个索引处

转载 作者:行者123 更新时间:2023-12-01 01:47:23 24 4
gpt4 key购买 nike

我有这个脚本,它一次从javascript数组中计数一个值,但问题是当最后一个计数到最后一个索引时,它再次从索引0开始,但我希望它停止在最后一个索引处。我使用 setInterval 使其继续运行。到目前为止,这是我的代码:我很感激你的时间。谢谢

<!DOCTYPE html>
<html>

<head>
<title>my page</title>
</head>

<body>
<h4>Counter</h4>
<span id="disp"></span>

<script>
var title = ['$0', '$30', '$47', '$257', '$657', '$1389', '$1557', '$2557'];

var i = 0; // the index of the current item to show

setInterval(function() { // setInterval makes it run repeatedly
document
.getElementById('disp')
.innerHTML = title[i++]; // get the item and increment i to move to the next
if (i == title.length) i = 0; // reset to first element if you've reached the end
}, 3000);
</script>
</body>

</html>

最佳答案

您可以存储间隔 ID,如果完成,请使用它调用 clearInterval 以停止间隔。

<h4>Counter</h4>

<span id="disp"></span>

<script>
var title = ['$0', '$30', '$47', '$257', '$657', '$1389', '$1557', '$2557'];

var i = 0; // the index of the current item to show

var interval = setInterval(function() { // setInterval makes it run repeatedly
document
.getElementById('disp')
.innerHTML = title[i++]; // get the item and increment i to move to the next
if (i == title.length) {
i = 0; // reset to first element if you've reached the end
clearInterval(interval);
}
}, 300);
</script>

关于javascript - 如何让这个javascript数组值循环并停在最后一个索引处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51848937/

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