立即运行和延迟0毫秒之间的差异

时间:2017-02-27 09:39:13

标签: javascript settimeout

我有一个比较的小例子:



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>
&#13;
&#13;
&#13;

VS

&#13;
&#13;
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);
&#13;
[contenteditable=true] {
  width: 100px;
  height: 20px;
  border: 1px solid #ccc;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div contenteditable="true"></div>
&#13;
&#13;
&#13;

事件的责任:在我输入一些文本到div后,按backspace键,它会将当前文本记录到控制台。

自从我将console.log($div.text());更改为setTimeout(() => console.log($div.text()));后,日志已更改。

WindowOrWorkerGlobalScope.setTimeout()提及milliseconds

  

执行代码之前等待的毫秒数。如果   省略,使用值0。

所以,我的问题是:为什么延迟0毫秒不同于在这种情况下立即运行?

更新(基于@ Seabizkit的评论)

&#13;
&#13;
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);
&#13;
[contenteditable=true] {
  width: 100px;
  height: 20px;
  border: 1px solid #ccc;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div contenteditable="true"></div>
&#13;
&#13;
&#13;

它将相同的结果记录到第一种情况。

0 个答案:

没有答案