JavaScript Closures and setTimeout

后端 未结 2 572
长发绾君心
长发绾君心 2021-01-20 02:33

Closures are something I still don\'t fully grasp in JS. I think this is a closure issue. I\'m trying to create a progress bar. Every x seconds I want to increment the width

2条回答
  •  轮回少年
    2021-01-20 02:45

    Instead of using setTimeout you want to use setInterval. The latter will call the function once per interval instead of just once.

    var width = 50
    setInternal(function () {
      myDiv.style.width = width
      width++
      }, timeIncrement * 1000);
    

    Additionally at some point you'll probably want to end the interval and stop incrementing the size. For that you'll need to call clearInterval on the result of setInterval

    var width = 50
    var t = setInterval(function () {
      myDiv.style.width = width
      width++
      if (doneIncrementing) {
        clearInterval(t);
      }
      }, timeIncrement * 1000);
    

提交回复
热议问题