首页 > 循环体中,dom 渲染问题

循环体中,dom 渲染问题

html 块
<p data-start="0" data-end="1999" class=".price">0</p>

var throttle = function (fn, delay) {
        var timer = null;
        var t_start;
        return function () {
            var context = this, args = arguments, t_curr = +new Date();
            clearTimeout(timer);
            if (!t_start) {
                t_start = t_curr;
            }
            if (t_curr - t_start >= 166) {
                fn.apply(context, args);
                t_start = t_curr;
            } else {
                timer = setTimeout(function () {
                    fn.apply(context, args);
                }, delay);
            }
        };
    }
function jump(elem) {
                var startNum = $(elem).data("start")
                    ,endNum = $(elem).data("end");
                for (; startNum < endNum; startNum++) {
                    requestAnimationFrame((function(startNum){
                        return throttle(function(){
                            elem.innerText = startNum;
                        },66)
                    })(startNum))
                }
        }

jump(document.querySelector('.price'));

requestAnimationFrame 中 callback 改写为

        requestAnimationFrame((function (startNum) {
            return function () {
                console.log(startNum);
                elem.innerText = startNum;
            }
        })(startNum))

不能动态修改视图数据,但是startNum 是一直自增的, 为什么需要 函数节流?


timer = setTimeout(function () {
    fn.apply(context, args);
}, delay);

函数节流2个目的:

【热门文章】
【热门文章】