nygmaaa
1/13/2019 - 1:45 PM

Snippets

Snippets

// setTimeout/setInterval's additional parameters which are passed through to the function specified by function or code once the timer expires.

// closure here, the variable `timer` will stay at the fourth loop.
function fn1() {
  for (var i = 0; i < 4; i++) {
    var timer = setTimeout(function (i) {
      console.log(i)
      clearTimeout(timer)
    }, 10, i)
  }
}

// the first `timer` is undefined, and the last `timer` hasn't cleared.
function fn2() {
  for (var i = 0; i < 4; i++) {
    var timer = setInterval(function (i, timer) {
      console.log(i)
      clearInterval(timer)
    }, 10, i, timer)
  }
}


fn1() // 0 1 2
fn2() // 0 1 2 3(infinite loop every 10 ms)