JavaScript实现模拟一个微任务 – MasterH杂货铺

JavaScript实现模拟一个微任务

/**
 * 异步执行一个函数
 * 如果可以,尽量将函数放入微队列中,考虑兼容性
 * @param { Function } func 无参,无返回
 */
function asyncRun(func) {
    if (typeof Promise !== 'undefined') {
        Promise.resolve().then(func)
    } else if (typeof MutationObserver !== 'undefined') {
        const ob = new MutationObserver(func);
        const textNode = document.createTextNode('0');
        ob.observe(textNode, {
            characterData: true
        });
        textNode.data = '1';
    } else {
        setTimeout(func)
    }
}

Related Posts

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注