猿问

如何在性能方面优化脚本

我有一个调用的函数ajaxCall(),它简单地在服务器上进行调用并从提要中返回一个值。


我想要做的是将值从提要保存到firstInterval变量,等待 10 秒,再次调用并将值保存到secondInterval变量。然后动画网页上这些数字的增加。这是我们目前所拥有的:


 setInterval(function(){

   getAmounts() 

}, 11000);


function getAmounts(){

  firstInterval = ajaxCall();

  setTimeout(() => {

    secondInterval = ajaxCall();

    animateValue('#bronze-price p', firstInterval, secondInterval, 10000)

  }, 10000);

};


  function animateValue(id, start, end, duration) {

    start = parseInt(start);

    end = parseInt(end);

    var range = end - start;

    var current = start;

    var increment = end > start? 1 : -1;

    var stepTime = Math.abs(Math.floor(duration / range));

    var obj = document.querySelector(id);

    var timer = setInterval(function() {

        current += increment;

        obj.innerHTML = current;

        if (current == end) {

            clearInterval(timer);

        }

    }, stepTime);

}

所以这个想法是有一个函数来获取第一个间隔,10秒后它会抓住第二个间隔并调用动画。这一切都包含在 setInterval 函数中,因此我可以反复平滑地更改数字。


但是我很确定这不是一个非常干净的解决方案,因为它包含setInterval在setTimeout另一个setInterval函数中。我也在控制台中收到了具有这两种功能的此类警告:


[违规] 'setInterval' 处理程序花费了 ms


跟进这个想法但优化代码的最佳方法是什么?


神不在的星期二
浏览 128回答 1
1回答

慕虎7371278

我认为Promises并使requestAnimationFrame这更容易处理,同时也摆脱setTimeout/setInterval. 一个例子是:// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#Getting_a_random_integer_between_two_values_inclusivefunction getRandomIntInclusive(min, max) {&nbsp; &nbsp; min = Math.ceil(min);&nbsp; &nbsp; max = Math.floor(max);&nbsp; &nbsp; return Math.floor(Math.random() * (max - min + 1)) + min;}// fake api endpointconst ajaxCall = () => new Promise(resolve => {&nbsp; &nbsp; setTimeout(resolve, 400, 1000 + getRandomIntInclusive(0, 1000));});// simple animation helper using requestAnimationFrameconst animate = (from, to, duration, cb) => {&nbsp; &nbsp; const start = performance.now();&nbsp; &nbsp; return new Promise(resolve => {&nbsp; &nbsp; &nbsp; &nbsp; requestAnimationFrame(function loop() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; const f = (performance.now() - start) / duration;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cb(from + Math.round(f * (to - from)));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; f < 1.0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ? requestAnimationFrame(loop)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; : resolve();&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; });};// main(async (interval) => {&nbsp; &nbsp; // where to output&nbsp; &nbsp; const dst = document.querySelector('#out');&nbsp; &nbsp; // initial value&nbsp; &nbsp; let prev&nbsp; = 0;&nbsp; &nbsp; // wait for next value of ajaxCall&nbsp; &nbsp; while (true) {&nbsp; &nbsp; &nbsp; &nbsp; const next = await ajaxCall();&nbsp; &nbsp; &nbsp; &nbsp; console.log(`animating: ${prev} -> ${next}`);&nbsp; &nbsp; &nbsp; &nbsp; // animate from `prev` to `next`&nbsp; &nbsp; &nbsp; &nbsp; await animate(prev, next, interval, current => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dst.innerHTML = current;&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; prev = next;&nbsp; &nbsp; }})(10000);<div id="out"></div>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答