$start = Date.now() $time_unfocus = 0; $time_focus = 0; $time_checkout = 0; $time_checkin = 0; $time_total = 0; $tabswitches = 0; $(window).focus(function() { $tabswitches += 1; $time_checkin = Date.now(); if($time_checkin == $start){ $time_checkin=0; $tabswitches -= 1; } else{ $time_unfocus = ($time_checkin - $time_checkout)/1000; $time_focus = ($time_checkin - $start - $time_unfocus)/1000; $time_total = ($time_focus + $time_unfocus); } }); $(window).blur(function() { $time_checkout = Date.now(); });