30秒学会 JavaScript 片段 · 2023年4月19日

30秒学会 JavaScript 片段 – Defer function invocation

Defers invoking a function until the current call stack has cleared.

  • Use setTimeout() with a timeout of 1 ms to add a new event to the event queue and allow the rendering engine to complete its work.
  • Use the spread (...) operator to supply the function with an arbitrary number of arguments.

代码实现

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

翻译自:https://www.30secondsofcode.org/js/s/defer-function