Skip to content

YY. MicroTask

微任务运行工具类, 用来解决大任务耗时从而导致页面卡顿的问题

  • 利用时间切片来切割任务
  • 利用Promise是微任务
  • 利用requestIdleCallback来进行任务调度

creation

  • constructor()

method

static runTaskAsync(options)

  • 运行微任务
  • 参数
  • {Object} options
    • {Function} options.run 任务函数
    • {Number} options.count 任务函数运行次数
  • 返回值: Promise

下面我们来演示个clone 100w对象的例子,来看看具体怎么使用

js
const now = YY.Util.now;

function createObject() {
    return {
        type: "Feature",
        geometry: {
            type: "Point",
            coordinates: [120.61868009903321, 31.16788501911506]
        },
        properties: {
            name: "2-8b54a3",
            _color: "",
            center: [120.61868009903321, 31.16788501911506, 0]
        }
    };
}

function cloneDataSync(data) {
    if (structuredClone) {
        return structuredClone(data);
    }
    return JSON.parse(JSON.stringify(data));
}

function generateData() {
    const data = [];
    while (data.length < 100 * 10000) {
        data.push(createObject());
    }
    return data;
}

const data = generateData();

//同步方法测试
function testSync() {
    const time = 'testSync';
    console.time(time);
    const t = now();
    const cloneData = cloneDataSync(data);
    const message = `testSync time:${now() - t}ms`;
    showMessage(message);
    console.timeEnd(time);
    console.log(cloneData);
}

//异步方法测试
function testAsync() {
    const time = 'testAsync';
    console.time(time);
    const t = YY.Util.now();
    const pageSize = 10000;
    const count = Math.ceil(data.length / pageSize);
    let page = 1;
    const run = () => {
        const startIndex = (page - 1) * pageSize,
            endIndex = (page) * pageSize;
        const list = data.slice(startIndex, endIndex);
        page++;
        return cloneDataSync(list);
    }
    YY.MicroTask.runTaskAsync({
        count,
        run
    }).then(results => {
        const list = [];
        results.forEach(result => {
            for (let i = 0, len = result.length; i < len; i++) {
                list.push(result[i]);
            }
        });
        const message = `testAsync time:${now() - t}ms`;
        showMessage(message);
        console.timeEnd(time);
        console.log(list);
    })
}

This document is generated by vitepress and Edit by deyihu