I'm having some trouble testing the performance of some code that heavily update the DOM.
To illustrate, i created a simple demo:
function insertListItem() {
let ul = document.querySelector('ul')
let start = new Date()
// heavy dom operations
for (let i = 0; i < N; i++) {
let li = document.createElement('li')
li.textContent = 'item' + i
ul.appendChild(li)
}
// log the duration (deferred by 0ms timer)
setTimeout(() => {
let t2 = new Date() - start
console.log(`t2: ${t2} ms`)
}, 0)
// log the duration instantly
let t1 = new Date() - start
console.log(`t1: ${t1} ms`)
}
let N = 100000
let btn = document.querySelector('button')
btn.addEventListener('click', insertListItem)
<section>
<button>insert list item</button>
<ul></ul>
</section>
The console output of t1
, t2
has a HUGE difference which is out of my expectation, the code above besides the timer are all synchronous. Because of the event loop the timer's callback would be pushed into the callback/event queue and waits for execution, this will surely results some extent of delay between t1
and t2
otherwise they're supposed to be roughly the same.
However, t1
behaves as if it's called before the rendering task
while t2
is called after the rendering task
as expected. What's the reason? How can i change the test for proper measurement?