如何使用setTimeout和clearTimeout实现计时器?



遍历用于显示的问题/答案数组。

const data = [
{
question: "xxx",
answer: "xxxx."
},
{
question: "xxx",
answer: "xxx?"
},
// etc, etc...

然后创建一个for循环,该循环创建一个article元素、按钮、h3和段落。然后,它将有文本内容的每个按钮,说'+',每次我点击按钮,它会显示答案,当我点击它隐藏。

我正在寻找一种方法来实现setTimout,它设置了一个计时器来揭示答案,然后一个clearTimeout来取消一旦时间到了。

const main = document.querySelector('main');
data.forEach(trivia => {
const article = document.createElement('article');
const button = document.createElement('button');
button.type = 'button';
button.textContent = '+';
button.addEventListener('click', () => {
button.textContent = p.classList.contains('hidden') ? '-' : '+';
p.classList.toggle('hidden');
});
article.appendChild(button);
const h3 = document.createElement('h3');
h3.textContent = trivia.question;
article.appendChild(h3);
const p = document.createElement('p');
p.textContent = trivia.answer;
p.classList.add('hidden');
article.appendChild(p);
main.appendChild(article);
});

在侦听器上添加setTimeout()将是一个很好的地方。

button.addEventListener('click', () => {
button.textContent = p.classList.contains('hidden') ? '-' : '+';
p.classList.toggle('hidden');
const timer = setTimeout(() => {
// code for hiding the element
clearTimeout(timer);
}, 5000); // 5 seconds
if (p.classList.contains('hidden')) {
clearTimeout(timer);
}
});

演示:

fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(users => {
for (const user of users) {
const section = document.createElement('section');
const label = document.createElement('label');
const button = document.createElement('button');
const paragraph = document.createElement('p');
label.textContent = user.name;
button.textContent = '+';
button.addEventListener('click', (event) => {
const btn = event.target;
const p = btn.nextElementSibling;
switch (p.style.display) {
case 'block':
btn.textContent = '+';
p.style.display = 'none';
break;
case 'none':
btn.textContent = '-';
p.style.display = 'block';
break;
}
const timer = setTimeout(() => {
btn.textContent = '+';
p.style.display = 'none';
clearTimeout(timer);
}, 5000);
if (p.style.display === 'none') {
clearTimeout(timer);
}
});
paragraph.style.display = 'none';
paragraph.textContent = JSON.stringify(user.address);
section.append(label);
section.append(button);
section.append(paragraph);
document.body.append(section);
}
})
.catch(error => {
console.error(error);
})
<html>
<body></body>
</html>