The web-server has no way of knowing when the user "left". A web server is only aware of each request, this is built into the very foundations of the web.
Having said that, take a look at this post by Quiz Guru Tim Hunt
https://moodle.org/mod/forum/discuss.php?d=278482