setInterval的另一setInterval的内加快随着时间的推移

问题描述 投票:0回答:2

我花了很长时间试图找出如何在与CSS样式宽松功能谷歌地图API折线动画的象征。我得到这个工作with this Gistthis Google Maps API example。现在,我尝试运行setInterval(myFunc, 10)每隔〜5秒。下面是相关的代码片段:

function animateCircle(line) {
    var count = 0;
    let refreshRate = 10;
    let countFunc = EasingFunctions.easeInOutCubic;
    let perc = 0

    function moveCircle() {
      count = count < 1 ? (count + 0.005) : 0;

      perc = countFunc(count) * 100 <= 100 ? countFunc(count) * 100 :  countFunc(count) * 100 - 100
      perc = perc >= 0 ? perc : 100 + perc
      perc === 0 ? window.clearInterval(moveCircInterval) : ''
      // console.log(count + " // " + perc)

      var icons = line.get('icons');
      icons[0].offset = perc + '%';

      line.set('icons', icons);
    }

    var moveCircInterval = window.setInterval(moveCircle, refreshRate);

    window.setInterval(() => moveCircInterval = window.setInterval(moveCircle, refreshRate), 5000)
  }

full JSFiddle to see it in action

此代码是不是很大,但几乎工作。在我结束,它的速度随着时间的推移,特别是如果你导航到该标签离开并返回。

javascript animation setinterval
2个回答
2
投票

如果我理解您的关注,我们正确的调整可以像下面的代码:

function animateCircle(line) {
    var count = 0;
    let refreshRate = 10;
    let countFunc = EasingFunctions.easeInOutCubic;
    let perc = 0

    function moveCircle() {
      count = count < 1 ? (count + 0.005) : 0;

      perc = countFunc(count) * 100 <= 100 ? countFunc(count) * 100 :  countFunc(count) * 100 - 100
      perc = perc >= 0 ? perc : 100 + perc
      if (perc === 0) {
        clearInterval(moveCircInterval);
        setTimeout(() => {
            moveCircInterval = setInterval(moveCircle, refreshRate);
        }, 5000);
    }

      var icons = line.get('icons');
      icons[0].offset = perc + '%';

      line.set('icons', icons);
    }

    var moveCircInterval = setInterval(moveCircle, refreshRate);
  }

请您尝试一下,让我知道它是否适合你!


0
投票

我落得这样做的:

function animateCircle(line) {
  var remove = window.setInterval(function() {
    var count = 0;
    let refreshRate = 20;
    let countFunc = EasingFunctions.easeInOutQuint;
    let perc = 0
    var now, before = new Date();
    var move = window.setInterval(function() {
      now = new Date();
      var elapsedTime = (now.getTime() - before.getTime());
      var icons = line.get('icons');

      if (elapsedTime > refreshRate + 5000) {
        // reset if navigate away from tab
        count = 0.005
        window.clearInterval(move)
      } else {
        count = count < 1 ? (count + 0.005) : 0;
      }

      perc = countFunc(count) * 100 <= 100 ? countFunc(count) * 100 : countFunc(count) * 100 - 100
      perc = perc >= 0 ? perc : 100 + perc
      perc === 0 || perc === 100 ? (window.clearInterval(move)) : ''

      icons[0].icon.path = svgTrans(perc)
      icons[0].offset = perc + '%';

      line.set('icons', icons);
    }, refreshRate)

  }, 5000)
}

here's the JSFiddle

© www.soinside.com 2019 - 2024. All rights reserved.