Reputation: 4429
Try this in chrome versus firefox/IE:
var cancelPressed = false;
function redirect() {
//window.location = "http://www.google.com";
alert('hi!');
}
window.onbeforeunload = function() {
window.pressedTimer = setInterval("cancelPressed = true; clearInterval(window.pressedTimer);",3000);
window.onbeforeunload = function() {
if (!cancelPressed) {
window.unloadTimer = setTimeout('redirect()',500);
window.onbeforeunload = function() {clearTimeout(window.unloadTimer);};
return "Redirecting..";
} else {
return 'wups';
}
};
return 'first!';
};
In FF/IE, refresh, hit cancel on the first prompt, wait about six seconds, and then try to refresh. The 'wups' will be triggered. However, in Chrome, you can wait as long as you want and cancelPressed will never be set to true.
What do you think?
Upvotes: 1
Views: 2461
Reputation: 19027
Which version of Chrome are you using? If I wait long enough, I also get the 'wups'
message in Chrome. However, I noticed a subtle difference between Webkit browsers and other browsers. Consider the following code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Javascript test</title>
<script type="text/javascript" language="javascript">
window.onload = function() {
document.getElementById("test").onclick = function() {
var startdate;
var interval = window.setInterval(function() {
// Get the difference (in milliseconds) between the current
// date and the startdate.
var diff = (new Date()).getTime() - startdate.getTime();
alert(diff);
window.clearInterval(interval);
}, 5000);
alert("Hello!");
startdate = new Date();
};
};
</script>
</head>
<body>
<button id="test">Test button</button>
</body>
</html>
In chrome and safari, the second alert will always display a number slightly greater than 5000, while in other browsers, you get a number between 0 and 5000.
So what is happening? With setInterval()
, the browser creates a timer that will invoke a javascript method every given interval. Javascript is single threaded, and an alert box will completely block the javascript execution. In chrome and safari, this means that the timer is also paused, while in other browsers the timer continues, but the javascript method invocation is suppressed until the alert box is closed.
What has this to do with your example? It means that in chrome and webkit you always have to wait at least 3000 milliseconds before cancelPressed
is set, while in others browser, this will happen somewhere between 0 and 3000 milliseconds.
Upvotes: 1