View Full Version : window unload event not firing

10-12-2011, 04:48 AM
i have aded window unload event handler to my code. my page calls some function that takes few secs and page then loads in 5-6 secs. while ths page is loading, if user clicks 'x' on browser window, then code inside unload event handler doesnt get executed. if user waits for page to be loaded fully and hten clicks 'x', then unload event handler gets executed. but i want if during loading user decides to click 'x' button, then also unload handler shold get exucted. i am pasting a sample code that simulates my situation:

<html xmlns="http://www.w3.org/1999/xhtml" >
<title>Untitled Page</title>
<script type="text/javascript">
function unloadPage() {
alert('unloaded page');
function pauseJS(timeInMilliS) {
var date = new Date();
var curDate = null;
do {
curDate = new Date();
}while(curDate-date < timeInMilliS);
<body onload="pauseJS(6000)" onunload="unloadPage()">
<p>Test Page</p>

Old Pedant
10-12-2011, 05:09 AM
That's because your pauseJS function is running for the entire 6 seconds and WHILE IT IS RUNNING IT LOCKS OUT EVERYTHING ELSE.

JavaScript is SINGLE-THREADED, meaning that any events that happen while JS code is running will simply wait until the JS code is finished.

You will have to find a way to allow the events to happen. Perhaps break your 6-second job into quarter-second pieces with a short window.timeout() in between each?