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.