Search code examples
javascriptdateonloadonbeforeunload

Subtract to function times


I currently have two functions that capture the current dates minute in which a user loads and leaves a page.

Is there a way to combine these functions so that I can get the difference?

Ex. User loads the page at 30, and leaves at 45
Therefore, 45-30 = 15 minutes 

Also is there any reason why my unload alert does not work on safari?

JAVASCRIPT

<script type="text/javascript">
  window.onload = function () {
    var currentdate = new Date();
    var hour = currentdate.getHours();
    var minutes = currentdate.getMinutes(); 
    var seconds = currentdate.getSeconds();
    alert("starts at " + minutes + " minutes");
  }

  window.onbeforeunload = function (e) {
    var currentdate = new Date();
    var hour = currentdate.getHours();
    var minutes = currentdate.getMinutes(); 
    var seconds = currentdate.getSeconds();
    return ("leaves at " + minutes + " minutes");
  }
</script>

Solution

  • Something like this ?

    var pageLoadTime;
    
    window.addEventListener("load", function () {
        pageLoadTime = (new Date()).getTime();
    });
    
    window.addEventListener("beforeunload", function (e) {
        var pageUnloadTime = (new Date()).getTime();
        var secondsPassed = Math.round((pageUnloadTime - pageLoadTime) / 1000);
    
        var hoursPassed = Math.floor(secondsPassed / 3600);
        secondsPassed = secondsPassed % 3600;
    
        var minutesPassed = Math.floor(secondsPassed / 60);
        secondsPassed = secondsPassed % 60;
    
        alert(hoursPassed + " hour(s), " + minutesPassed + " minute(s), " + secondsPassed + " second(s)");
    });