亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在性能方面優化腳本

如何在性能方面優化腳本

神不在的星期二 2022-05-26 15:42:03
我有一個調用的函數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跟進這個想法但優化代碼的最佳方法是什么?
查看完整描述

1 回答

?
慕虎7371278

TA貢獻1802條經驗 獲得超4個贊

我認為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_inclusive

function getRandomIntInclusive(min, max) {

    min = Math.ceil(min);

    max = Math.floor(max);


    return Math.floor(Math.random() * (max - min + 1)) + min;

}


// fake api endpoint

const ajaxCall = () => new Promise(resolve => {

    setTimeout(resolve, 400, 1000 + getRandomIntInclusive(0, 1000));

});


// simple animation helper using requestAnimationFrame

const animate = (from, to, duration, cb) => {

    const start = performance.now();


    return new Promise(resolve => {

        requestAnimationFrame(function loop() {

            const f = (performance.now() - start) / duration;


            cb(from + Math.round(f * (to - from)));


            f < 1.0

                ? requestAnimationFrame(loop)

                : resolve();

        });

    });

};


// main

(async (interval) => {

    // where to output

    const dst = document.querySelector('#out');


    // initial value

    let prev  = 0;


    // wait for next value of ajaxCall

    while (true) {

        const next = await ajaxCall();


        console.log(`animating: ${prev} -> ${next}`);


        // animate from `prev` to `next`

        await animate(prev, next, interval, current => {

            dst.innerHTML = current;

        });


        prev = next;

    }

})(10000);

<div id="out"></div>


查看完整回答
反對 回復 2022-05-26
  • 1 回答
  • 0 關注
  • 107 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號