First, it's better to use window.addEventListener("blur", function() {}) to wait for the blur event, then set a callback function that will run once the window or the tab has lost focus.
For the callback function you should consider using the setTimeout global method that sets a timer which executes a function or specified piece of code once the timer expires. In your case let's say we want the title to say first "Come back", then after 3 seconds it'll say "Don't forget", and after another 3 secends "Where did you go?", the callback function will look like this:
function() {
document.title = "Come Back";
setTimeout(() => {
document.title = "Don't forget";
}, 3000); // Runs after 3 seconds of inactivity
setTimeout(() => {
document.title = "Where did you go?";
}, 6000); // Runs after 6 seconds of inactivity
}
Another remark is that the focus event handler you implemented replaces the document.title by original which is a reference to document.title itself and will return the same current title. Instead, the original title should be stored as a hard-coded string and then used to replace the title when the window is focused.
Wrapping everything up, the final code will look like this:
<script>
const original = "Original title";
window.addEventListener("focus", function () {
document.title = original;
});
window.addEventListener("blur", function () {
document.title = "Come Back";
setTimeout(() => {
document.title = "Don't forget";
}, 5000);
setTimeout(() => {
document.title = "Where did you go?";
}, 5000);
});
</script>
If this answer was helpful, an upvote would be appreciated.