2

I've a small example to compare:

let div_onKeydown = function (e) {
  let $div = $(this);
  
  let code = e.which;
  
  if (code === 8) {

    console.log($div.text());

  }
};

$('[contenteditable=true]').on('keydown', div_onKeydown);
[contenteditable=true] {
  width: 100px;
  height: 20px;
  border: 1px solid #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div contenteditable="true"></div>

vs

let div_onKeydown = function (e) {
  let $div = $(this);
  
  let code = e.which;
  
  if (code === 8) {
    
    setTimeout(() => console.log($div.text()));
    
  }
};

$('[contenteditable=true]').on('keydown', div_onKeydown);
[contenteditable=true] {
  width: 100px;
  height: 20px;
  border: 1px solid #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div contenteditable="true"></div>

The responsibility of the event: After I type some text into the div, press backspace key, it logs the current text to console.

Since I changed console.log($div.text()); to setTimeout(() => console.log($div.text()));, the log had been changed.

WindowOrWorkerGlobalScope.setTimeout() mentions about milliseconds:

The number of milliseconds to wait before executing the code. If omitted, the value 0 is used.

So, my question is: why is delaying 0 millisecond different from running immediately in this case?

UPDATE: (based on @Seabizkit's comment)

let div_onKeydown = function (e) {
  let $div = $(this);
  
  let code = e.which;
  
  if (code === 8) {
    console.log($div.text());
    
    setTimeout(console.log($div.text()));
  }
};

$('[contenteditable=true]').on('keydown', div_onKeydown);
[contenteditable=true] {
  width: 100px;
  height: 20px;
  border: 1px solid #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div contenteditable="true"></div>

It logs same result to the first case.

Tân
  • 1
  • 15
  • 56
  • 102
  • I'm guessing you'll find your answer here: http://stackoverflow.com/questions/779379/why-is-settimeoutfn-0-sometimes-useful – NoelB Feb 27 '17 at 09:47
  • I wanted to post, setting it before being deferred gives the exspected outcome `let div_onKeydown = function (e) { let $div = $(this); let code = e.which; if (code === 8) { var test = $div.text(); console.log(test); setTimeout(() => console.log(test)); } }; $('[contenteditable=true]').on('keydown', div_onKeydown);` – Seabizkit Feb 27 '17 at 09:56
  • @Seabizkit I just try, I gave same result to the first case :) – Tân Feb 27 '17 at 10:03
  • @TânNguyễn i don't think you followed me to well...please double check... `var test = $div.text();` capture the value before the deferring. – Seabizkit Feb 27 '17 at 10:14

0 Answers0