简体   繁体   English

在 javascript 闭包中使用 setInterval

[英]Using setInterval inside javascript closures

I am new to javascript and reading about closures currently.我是 javascript 的新手,目前正在阅读有关关闭的信息。 I was trying to implement an example to better understand the concept.我试图实现一个例子来更好地理解这个概念。

This is the snippet:这是片段:

function getValue() {
  let a = 0

  const runner = async () => {
    a += 1
  }

  setInterval(runner, 100)
  
  return () => {
    return a
  }
}

let value = getValue()
console.log(value()) -----> logging statement 1

// some long operation

console.log(value()) -----> logging statement 2

However, the output that I see is:但是,我看到的 output 是:

1
1

I expected the two logging statements to output two different values.我期望两个日志语句 output 有两个不同的值。 My understanding is that once getValue() is called, the runner function would execute at regular intervals.我的理解是,一旦调用getValue()runner程序 function 就会定期执行。 The variable a would get updated and hence the 2nd console.log should have printed an incremented value of a .变量a将得到更新,因此第二个console.log应该打印一个递增的a值。

You are almost there except missed the main part.除了错过主要部分外,您几乎就在那里。

Operations are happening too fast.操作发生得太快了。 It does not take 100 milliseconds to run the second iteration so the value remains the same.运行第二次迭代不需要 100 毫秒,因此值保持不变。

Try to wait at least 100 milliseconds since the interval you have needs that amount of time to increment.尝试至少等待 100 毫秒,因为您的时间间隔需要增加该时间量。

As shown in the example below.如下例所示。

 function getValue() { let a = 0 const runner = async () => { a += 1 } setInterval(runner, 100) return () => { return a } } let value = getValue() console.log(value()) // operations are happening too fast setTimeout(() => console.log(value()), 100); setTimeout(() => console.log(value()), 200); setTimeout(() => console.log(value()), 300);

function getValue() {
  let a = 0

  const runner = () => {
    a += 1
    console.log("Runner's A: " +a)
  }

  setInterval(runner, 100)
  
  return () => {
    return a
  }
}

let value = getValue()
console.log(value());// -----> logging statement 1

// some long operation

console.log(value());// -----> logging statement 2

https://jsbin.com/geponejuba/edit?js,console,output https://jsbin.com/geponejuba/edit?js,console,output

as pointed out above js is single threaded, and so the way it works is, your log statements are executed 1st and if there is nothing else to do, then setTimeout/setInterval are executed (this is a extremely simplified statement, You can read about "Event loop" for a detailed version)正如上面所指出的,js是单线程的,所以它的工作方式是,你的日志语句首先执行,如果没有别的事情要做,那么 setTimeout/setInterval 会被执行(这是一个非常简化的语句,你可以阅读详细版本的“事件循环”)

on the example jsbin i shared you can see the setInterval is getting called and is indeed updating the value.在我分享的示例 jsbin 中,您可以看到 setInterval 被调用并且确实在更新值。

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

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