2

when i run the following code (by clicking the button):

const div = document.querySelector( "div" )
const button = document.querySelector( "button" )
button.addEventListener( "click", () => {
    console.log( 'clicked' );
    div.textContent = 'printing....';
    var delay = 3000 + new Date().getTime();
    while ( new Date().getTime() < delay ) { }
    console.log( 'after delay' );
} );
<button>Run</button>
<div></div>

div's content appears after the callback has finished, so i got upon clicking the first log ( 'clicked') and then after the 3s delay loop the second log ( 'after delay' ) and the text inside the div. Why div.textContent = 'printing....'; isn't executed after the first console.log() ? Thanks a lot (i'm new in coding and in stackoverflow , so please forgive me if i'm unclear or silly)

Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
Giorgos
  • 65
  • 1
  • 5

1 Answers1

4

Javascript is single threaded (for the most part). You're locking up the thread with a busy loop, so the browser will not get a chance to update the page with your changes until your function finishes.

Instead, you'll want to make some changes, then set a timeout, then return, allowing the browser to paint. Later, when the timeout goes off, you can make some more changes.

button.addEventListener( "click", () => {
  console.log( 'clicked' );
  div.textContent = 'printing....';
  setTimeout(() = > {
    console.log('after delay');
  }, 3000);
});
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
  • 1
    To add up to this - Manipulations like `.textContent = ` related to DOM are part of Web API which is not part of immediately executable code in the current execution context. So, we have to wait for the event loop to do its turn thingy. – Oorja May 01 '19 at 18:55