// for(var sim = 0; sim < 3; sim++){
// setTimeout(function(){
// console.log(sim)
// }, sim*1000)
// }

  • 실행 컨텍스트에서 setTimeout은 queue에 대기하여 있다가 for 문이 끝나면 그때 stack으로 이동하여 실행되는데 이때 변수를 for문이 끝난 시점의 변수인 3을 출력한다.

for(var i=0; i<5; i++){
function timer(j){
setTimeout(function(){
console.log(j)
}, j * 1000)
}
timer(i)
}
- 결과는 0 부터 4 까지 1초마다 출력 .

  • timer 가 실행되면 j 값과 함께 scope가 생성된다.
  • setTimeout은 j를 참조하게 된다.

for(let k = 0; k < 5; k++){
setTimeout(function(){
console.log(k)
}, k*1000)
}

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Basic React App from Scratch && Webpack 4 Config

5 Useful Things The Spread Operator Can Do in JavaScript

The Spread Operator in JavaScript.

Microfrontends With React

ReactJS performance optimization

Issue 22/08

4 things that I’d like to see gone from JavaScript development forever

The Ultimate Test of Your Knowledge Is Your Capacity to Convey it to Another

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
blossom0417

blossom0417

More from Medium

Implementing Associative Arrays with Hash Maps: A Look Inside JavaScript Objects

Intro to Linked Lists (JavaScript) — Singly Linked List

I have never had the privilege to use dynamic imports until very recently when I used them to power…

What is the difference between Promise, Generator, and Async?