簡體   English   中英

如何使用 setTimeout 和 clearTimeout 實現計時器

[英]How can I implement a timer using setTimeout and clearTimeout

我遍歷我曾經顯示的問題/答案數組。

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

然后我創建一個 for 循環來創建文章元素、按鈕、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);
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM