0

我有一个数字计数器脚本。

var $findme = $('#numbers');
var exec = false;

function Scrolled() {
  $findme.each(function() {
    var $section = $(this),
      findmeOffset = $section.offset(),
      findmeTop = findmeOffset.top,
      findmeBottom = $section.height() + findmeTop,
      scrollTop = $(document).scrollTop(),
      visibleBottom = window.innerHeight,
      prevVisible = $section.prop('_visible');

    if ((findmeTop > scrollTop + visibleBottom) ||
      findmeBottom < scrollTop) {
      visible = false;
    } else visible = true;

    if (!prevVisible && visible) {
      if (!exec) {
        $('.fig-number').each(function() {
          $(this).prop('Counter', 0).animate({
            Counter: $(this).text()
          }, {
            duration: 2000,
            step: function(now) {
              $(this).text(Math.ceil(now));
              exec = true;
            }
          });
        });
      }
    }
    $section.prop('_visible', visible);
  });

}


function Setup() {
  var $top = $('#top'),
    $bottom = $('#bottom');

  $top.height(500);
  $bottom.height(500);

  $(window).scroll(function() {
    Scrolled();
  });
}
$(document).ready(function() {
  Setup();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="hww-whyus-item-num" id="numbers"> <span>0</span> <span class="fig-number">9</span> </div>

我需要添加重复计数'n'次的功能:例如计数从00到05开始,然后从00到05再次重复三次。或者它可以是随机数,但最重要的是最终数字 - 我需要能够创建具有变化数字的动画,但我需要控制动画的最终数字和总时间。

4

1 回答 1

0

也许你可以使用这样的承诺

// number of runs
var times = 3;
// number of items
var items = 6;
 
// makes a promise which will resolve when all items are made
let makeItem = () => {
  return new Promise( (done) => {
    for(var i = 0; i < items; i++){
       console.log('Item #0' + i);
    }
    done();
  });
}
// run asynchronoulsy and wait until makeItem is done to execute next iteration
let run = async () => {
  for(var i = 0; i < times; i++){
       console.log('Run #' + (i + 1));
      await makeItem();
    }
}

run();

编辑:对不起,您的代码使用 jquery,所以我也使用 jquery 更新了我的答案:

// number of runs
var times = 3;
// number of items
var items = 6;

container = $("#container");

function makeItem(it, el) {
  for(var x = 0; x < it; x++)
  {
    el.append("<li>item #0"+x+"</li>");
  }
}

async function run(times){
    let result;
  for(var i = 0; i < times; i++){
    container.append("<h2>Run #"+(i + 1)+"</h2>");
    try{
      result = await makeItem(items, container);
    }catch(error){
        console.log(error);
    }
  }
}

run(times);
于 2021-01-27T02:12:50.140 回答