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' );
} );

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)

1 Answers

Nicholas Tower On

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