6

Consider the following JavaScript code, with an animation library (i.e. scriptaculous) to boot.

window.onbeforeunload = function(event) {
    document.body.fade();
}

Leaving the page is instantaneous and doesn't wait for the animation to complete. Even though everywhere I look people say JS doesn't support threads, something is running in parallel here, because it seems the one will not wait for the other. Am I right about the threads, and is there any way to achieve what I'm trying to do here?

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
Johan Fredrik Varen
  • 3,604
  • 7
  • 31
  • 41

1 Answers1

0

A bit late but I think give an answer is interesting for futur SO users.

So there is multiple way to sync your code to this and so you should add a custom waiter.

window.onbeforeunload = function(event) {
    document.body.fade();
    while ((new Date()).getTime() < (new Date()).getTime()) + (1 *1000));
}

I guess you could also try with promises:

function sleep(time) {
  return new Promise((resolve) => {
    setTimeout(() => {
      return resolve(null);
    }, time);
  });
}

window.onbeforeunload = async function(event) {
    document.body.fade();
    await sleep(1 * 1000);
}
Saren
  • 888
  • 4
  • 10
  • 22