简体   繁体   中英

Using setInterval inside javascript closures

I am new to javascript and reading about closures currently. 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:

1
1

I expected the two logging statements to output two different values. My understanding is that once getValue() is called, the runner function would execute at regular intervals. The variable a would get updated and hence the 2nd console.log should have printed an incremented value of 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.

Try to wait at least 100 milliseconds since the interval you have needs that amount of time to increment.

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

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)

on the example jsbin i shared you can see the setInterval is getting called and is indeed updating the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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