Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the document.onreadystatechange function executed in advance?

console.time('onload')
console.time('onreadystatechange')
window.onload = ()=>{console.log('onload'); console.timeEnd('onload')}
document.onreadystatechange = ()=>{console.log('onreadystatechange');console.log(document.readyState);console.timeEnd('onreadystatechange')}

I wrote the above code in an inline script, why the result is the following?

In theory, console.time('onreadystatechange') should be executed first, but from the results, the onreadystatechange event is executed first, and document.readyState is ‘complete’, why is the event advanced?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There will be other state changes before document.readyState becomes complete.

At that time, the onreadystatechange function will be triggered.

console.timeEnd('onreadystatechange') is used in onreadystatechange.

When console.timeEnd is called, the timer corresponding to this record is cleared.

So when the subsequent onreadystatechange function is called again, there will be a prompt because there is no restart to set the onreadystatechange timer.

The entire execution sequence is consistent with the standard definition, and there is no problem.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading