defer - 延迟调用

优质
小牛编辑
127浏览
2023-12-01

延迟调用一个函数,直到当前调用堆栈已经清除。

使用 setTimeout() ,超时时间为1ms,将新事件添加到浏览器事件队列,并允许渲染引擎完成其工作。使用展开 (...) 运算符为函数提供任意数量的参数。

const defer = (fn, ...args) => setTimeout(fn, 1, ...args);
// Example A:
defer(console.log, 'a'), console.log('b'); // logs 'b' then 'a'

// Example B:
document.querySelector('#someElement').innerHTML = 'Hello';
longRunningFunction(); //Browser will not update the HTML until this has finished
defer(longRunningFunction); // Browser will update the HTML then run the function