如何在展示完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
相关产品推荐
相关产品推荐

