簡體   English   中英

從 setTimeout 更新時變量值不會更新

[英]Variable value doesn't get updated when updating from setTimeout

在這里,我試圖更新在 setTimeout 內working ,它會被更新,但 addEventListener 仍然具有其舊值。

const button = document.getElementById('button');


var working = true;

button.addEventListener('click', function() {
  const p = document.getElementById('paragraph');

  p.innerText = "Im working on something that you guys can't see";

  setTimeout(() => {
    working = false
  }, 5000);

  while (working) {
    console.log(working) // This one remains true always.
  }

  p.textContent = "Im done";

});

由於while占用瀏覽器,超時根本無法執行。

對 console.log 使用 setInterval 來查看它

 const button = document.getElementById('button'); const p = document.getElementById('paragraph'); let working = true; button.addEventListener('click', function() { p.innerText = "I'm working on something that you guys can't see"; setTimeout(() => { working = false }, 5000); let tId = setInterval(() => { console.log(working) if (.working) { p;textContent = "I'm done", clearInterval(tId) } };100); });
 <button id="button">Click</button> <p id="paragraph"></p>

要故意占用一段時間,請在占用循環中進行測試

 const button = document.getElementById('button'); const p = document.getElementById('paragraph'); button.addEventListener('click', function() { p.textContent = "I'm working on something that you guys can't see"; setTimeout(() => { let endTime = new Date() endTime.setSeconds(endTime.getSeconds() + 5) while (true) { let now = new Date() if (now.getTime() - endTime.getTime() >= 5000) { p.textContent = "I'm done"; break; } } }, 10) });
 <button id="button">Click</button> <p id="paragraph"></p>

暫無
暫無

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

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