简体   繁体   English

JavaScript 函数在两个不同的时间间隔给出两种不同的结果

[英]JavaScript Function gives two different results at two different intervals of time

I tried to look about this problem but didn't quite understand why does my code log out the first assignment before the delay and logs out the second assignment after the delay我试图查看这个问题,但不太明白为什么我的代码在延迟之前注销第一个分配并在延迟后注销第二个分配

let myName = 'John';
delayer();
myName = 'Robert';
function delayer() {
    console.log(myName);
    setTimeout(() => console.log(myName), 1500)
}

() => console.log(myName) is the same as function() { return console.log(myName); } () => console.log(myName)function() { return console.log(myName); } function() { return console.log(myName); } . function() { return console.log(myName); } . [1] [1]

The resulting function reference is passed to setTimeout which arranges to call it after the specified delay.结果函数引用被传递给setTimeout ,它安排在指定的延迟后调用它。 setTimeout doesn't wait for the delay to occur before returning. setTimeout在返回之前不会等待延迟发生。 It returns immediately.它立即返回。 So myName has been changed by the time the anonymous function has been called.因此在调用匿名函数时myName已更改。


  1. There are differences between the two approaches as itemized in the first link, but they don't come into play here.第一个链接中逐项列出的两种方法之间存在差异,但它们在此处不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM