Reputation: 993
I've added some Javascript code to my website which changes the title tag when the tab is not in focus.
It changes the title to a randomized phrase and toggles back to the original title every few seconds or so.
The code almost works, but I'd like the toggling of the title to stop when the tab comes back into focus. At the moment, the toggling carries on happening after the visitor clicks on the tag.
I assume this is due to the timeout function not stopping, but I am not sure. Also, currently, it sometimes displays one random phrase, then another before reverting back to the original title. I'd really like it show one random title then revert back, then show another random title.
Here is my current code:
<script>
var title = document.title;
var blurMessage = new Array("Please come back! :-( ", "Don't you love me anymore? :-(", "Fancy a cookie? ", "I'm feeling lonely :-( ");
window.onblur = function ()
{
setInterval(function()
{
var rand = Math.floor((Math.random() * blurMessage.length));
document.title = blurMessage[rand];
setTimeout(function()
{
document.title = title;
},4000);
},12000);
}
window.onfocus = function () { document.title = title; }
</script>
Upvotes: 3
Views: 2848
Reputation: 65806
Yes, you need to cancel the timer. To do that, you need to store a reference to the timer id as shown below.
I've also updated your code to use array literal syntax ([]
instead of new Array()
, which is shorter and more commonly used) and .addEventListener()
instead of onXyx
event properties because it is more robust and follows modern web standards for event handling.
Also, get into the habit of putting the opening curly brace for a block of code on the same line as the block's declaration.
Do this:
function foo() {
}
Instead of this:
function foo()
{
}
It can actually make a difference in how the code executes in certain circumstances and is considered a best-practice.
var title = document.title;
var blurMessage = [
"Please come back! :-( ",
"Don't you love me anymore? :-(",
"Fancy a cookie? ",
"I'm feeling lonely :-( "
];
var intervalTimer = null;
var timeoutTimer = null;
window.addEventListener("blur", function () {
intervalTimer = setInterval(function() {
var rand = Math.floor((Math.random() * blurMessage.length));
document.title = blurMessage[rand];
timeoutTimer = setTimeout(function() {
document.title = title;
},4000);
},12000);
});
window.addEventListener("focus", function(){
clearInterval(intervalTimer);
clearTimeout(timeoutTimer);
document.title = title;
});
Upvotes: 4