简体   繁体   中英

Variable value doesn't get updated when updating from setTimeout

Here I'm trying to update working inside the setTimeout it gets updated but the addEventListener still has its old value.

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";

});

The timeout is simply not able to execute due to the while hogging the browser.

Use setInterval for the console.log to see it

 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>

To hog on purpose for a time, test in the hogging loop

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM