I recently found the following question online:
Write a function that takes an object and appends it to the DOM, making it so that events are buffered until the next tick? Explain why this is useful?
Here is my response:
function appendElement(element) {
setTimeout(function() {
document.body.appendChild(element);
}, 0);
}
Why did I set the interval to zero?
According to this article, setting the timeout to 0, delays the events until the next tick:
The execution of func goes to the Event queue on the nearest timer tick. Note, that’s not immediately. No actions are performed until the next tick.
Here's what I am uncertain of:
- Is my solution correct?
- I cannot answer why this approach is beneficial
For reference, I got this question from this website listing 8 JavaScript interview questions.
I'd also like to point out that I am asking this question for my own research and improvement and not as part of a code challenge, interview question, or homework assignment.