JavaScript高级程序设计之函数性能

setTimeout 比 setInterval 性能更好

// 取代setInterval
setTimeout(function self () {
    
    // code goes here

    setTimeout(self, interval);
}, interval);

对异步执行的大数组的分割执行

// 大块、异步数组的处理
function chunk(arr, process, context) {
    setTimeout(function self() {

        var item = arr.shift();
        process.call(context, item);

        if (arr.length > 0) {
            setTimeout(self, 100)
        }
    }, 100)
}

var arr = ["123", "456", "789", "123", "456", "789", "123", "456", "789"],
    process = function (item) {
        console.log(item);
    };

// arr.concat() 返回arr数组的一个副本;否则chunk后arr成为了空数组
chunk(arr.concat(), process);

函数节流

// 函数节流,某些代码没必要没有间断的连续重复执行,如winddow.onresize = function(){ throttle(fn); }
function throttle(method, context) {
    clearTimeout(method.tId);

    method.tId = setTimeout(function () {
        method.call(context)
    }, 100)
}

window.onscroll = function () {
    throttle(function () {
        console.log(document.documentElement.scrollTop);
    });
};

 

posted @ 2014-06-12 13:51  farawayfromhome  阅读(284)  评论(0编辑  收藏  举报