Skip to content

Instantly share code, notes, and snippets.

@glasner
Created February 26, 2012 21:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glasner/1919166 to your computer and use it in GitHub Desktop.
Save glasner/1919166 to your computer and use it in GitHub Desktop.
AJAX on beforeunload for Chrome
sleep = (duration) ->
milliseconds = -> new Date().getTime()
start = milliseconds()
runningFor = milliseconds() - start
while runningFor < duration
runningFor = milliseconds() - start
$('div') # has to actually do something for it to work
window.addEventListener 'beforeunload', (e) ->
# make *sync* ajax call
sleep 1000
return undefined
@glasner
Copy link
Author

glasner commented Feb 26, 2012

If the beforeunload handler times out, Chrome will run previous code but not show the "Do you want to leave" dialog.

@glasner
Copy link
Author

glasner commented Feb 26, 2012

Should mention the code to sleep was born from http://www.phpied.com/sleep-in-javascript/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment