JSFiddle - React, Tailwind, and code Playground

by sanjaydookhoo

HTML

<p>
  Click into this white box to test window focused, and out of this white box to test window losing focus. This is a unique case for this, because jsfiddle isolated environment treats this white box as the window/tab.
</p>
<b id='id'>

</b>

JavaScript

let prevStateIsFocused = null // used to ensure that there is only one execution of a function for either the document focused or not

setInterval(() => {
	if(document.hasFocus()){
		if(prevStateIsFocused !== true){
			console.log('window is focused')
			// execute some function here ...
      document.getElementById('id').innerHTML = 'window is focused'
		}
		prevStateIsFocused = true
	}else{
		if(prevStateIsFocused !== false){
			console.log('window has lost focused, blurred')
			// execute some function here ...
      document.getElementById('id').innerHTML = 'window has lost focused, blurred'
		}
		prevStateIsFocused = false
	}
}, 500)