I want to check if the user changed the view of the current tab, that's why I am testing with if
condition on document.hasFocus()
and if it's equal to False, then I send an Axios(ajax) request to the backend..
Right now I am using document.hasFocus()
with setInterval()
function! In my case and using the setInterval function, the function checkFocus
got triggered every 2 Seconds and checks if the user hasFocus.
The result of this is => if the user changes the tab.. => every 2 seconds an ajax request is sent .. (because of the setInterval) While I want the event to be triggered only 1 time. I want to send only 1 ajax request Each time the user loses the focus..
That's why I can"t use the SetInterval Function. My question is: How can I Listen to document.hasFocus without using SetInterval Function?
Here is my code:
setInterval( checkFocus, 200 ); function checkFocus() { if ( document.hasFocus() == false ) { axios.post(url).then(function(response){ }).catch(function(error) { window.alert("Ouch an unexpected error has occurred. Reload the page and try again"); }); } }
https://stackoverflow.com/questions/65819464/how-can-i-listen-to-document-hasfocus-without-using-an-interval January 21, 2021 at 08:10AM
没有评论:
发表评论