Javascript:优化用于自动更改图像的脚本



我有一个简单的Javascript脚本,它在后台循环5个图像

trainer01的第一个图像已经在HTML文件中。

我的脚本运行良好,但我确实需要对其进行优化,使其更加整洁。现在,当我需要更改转换之间的秒数时,我需要更改每次更改的setTimeout,然后更改setInterval。

所以我需要更多的微小和优化。关于如何获得上面所写的内容,有什么选择吗?

我的脚本:

const herotrainers = document.getElementById("herotrainers");
function trainerChanger() {
setTimeout(
function() {
herotrainers.className = '';
herotrainers.classList.add('trainer02');
}, 3000);
setTimeout(
function() {
herotrainers.className = '';
herotrainers.classList.add('trainer03');
}, 6000);
setTimeout(
function() {
herotrainers.className = '';
herotrainers.classList.add('trainer04');
}, 9000);
setTimeout(
function() {
herotrainers.className = '';
herotrainers.classList.add('trainer05');
}, 12000);
setTimeout(
function() {
herotrainers.className = '';
herotrainers.classList.add('trainer01');
}, 15000);
}
trainerChanger();
setInterval(function() {
trainerChanger();
}, 15000);

我喜欢使用生成器函数来处理"区间循环"(它使用的方法与我对另一个SO问题的回答相同(:

const iterator = function*(){
const classNames = [
'trainer01',
'trainer02',
'trainer03',
'trainer04',
'trainer05',
]
const herotrainers = document.getElementById("herotrainers");

while(true){ //Repeat indefinitely
for(const elem of classNames){
herotrainers.classList.add(elem)
yield //Wait here
herotrainers.classList.remove(elem)
}
}
}()
setInterval(() => iterator.next(), 3000)
iterator.next() //Call it immediately for the first time
/* Some irrlevant stlyes to display the active class */
#herotrainers.trainer01::after{content:'.trainer01';color:red}#herotrainers.trainer02::after{content:'.trainer02';color:#ff0}#herotrainers.trainer03::after{content:'.trainer03';color:green}#herotrainers.trainer04::after{content:'.trainer04';color:#00f}#herotrainers.trainer05::after{content:'.trainer05';color:#ff00ff}
<div id="herotrainers">Active class: </div>

考虑使用异步循环。不需要同时分配classNameclassList.add-只需设置整个className:

const elm = document.getElementById("herotrainers");
const delay = ms => new Promise(res => setTimeout(res, ms));
async function trainerChanger() {
for (let i = 2; i <= 5; i++) {
await delay(3000);
elm.className = 'trainer0' + i;
}
await delay(3000);
elm.className = 'trainer01';
trainerChanger();
}
trainerChanger();

我会将区间标准存储在一个数组中,然后循环通过它。

将标准放在数组中可以很容易地进行调整。

function trainerChanger () {
const intervals = [
{delay: 3000, className: 'trainer01'},
{delay: 6000, className: 'trainer03'},
{delay: 9000, className: 'trainer04'},
{delay: 12000, className: 'trainer05'},
{delay: 15000, className: 'trainer01'}
];
intervals.forEach(interval => {
const {delay, className} = interval;
setTimeout(className => {
herotrainers.className = className;
}, delay);
});
}

最新更新