You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在展示完Word6后停止text-rotator的轮播超时?

解决轮播器展示完最后一项后停止的问题

你的代码之所以会无限循环,是因为用了取余运算符让index始终在数组范围内循环,并且每次执行rotate都会无条件调用setTimeout。要在展示完Word6后停止,只需要在调用下一次setTimeout前判断是否已经遍历完所有元素即可,这里提供两种简单的修改方式:

方式一:判断当前是否为最后一项

const phrases = ['Word1', 'Word2', 'Word3', 'Word4', 'Word5', 'Word6'];
let index = 0;

function rotate() {
  document.getElementById('text-rotator').innerText = phrases[index];
  // 如果当前已经是最后一个元素,直接返回不再继续
  if (index === phrases.length - 1) {
    return;
  }
  index++;
  setTimeout(rotate, 700);
}

rotate();

方式二:判断索引是否超出数组范围

const phrases = ['Word1', 'Word2', 'Word3', 'Word4', 'Word5', 'Word6'];
let index = 0;

function rotate() {
  document.getElementById('text-rotator').innerText = phrases[index];
  index++;
  // 只有当索引还没到数组末尾时,才继续设置下一次轮播
  if (index < phrases.length) {
    setTimeout(rotate, 700);
  }
}

rotate();

两种方式都能实现需求:当展示完Word6后,不再触发下一次setTimeout,轮播器自然停止。

内容的提问来源于stack exchange,提问作者Andreas Thomsson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 17:21:02