Lewis Day Lewis Day - 2 months ago 17
Javascript Question

Finish script on original document.title?

The problem I have is that this script finishes on the flash title what would I have to change so that this script finishes with the original document title. Hopefully you understand what I'm trying to achieve.

(function () {

var original = document.title;
var timeout;

window.flashTitle = function (newMsg, howManyTimes) {
function step() {
document.title = (document.title == original) ? newMsg : original;

if (--howManyTimes > 0) {
timeout = setTimeout(step, 1000);
};
};

howManyTimes = parseInt(howManyTimes);

if (isNaN(howManyTimes)) {
howManyTimes = 5;
};

cancelFlashTitle(timeout);
step();
};

window.cancelFlashTitle = function () {
clearTimeout(timeout);
document.title = original;
};

}());
flashTitle("New Notification");

You You
Answer

You need to make sure that the howManyTimes var is an even number, if it is an odd number, it will end on the newMsg:

(function () {

    var original = document.title;
    var timeout;

    window.flashTitle = function (newMsg, howManyTimes) {
        if (isNaN(howManyTimes)) {
            howManyTimes = 5;
        };

        howManyTimes = (howManyTimes % 2 == 0) ? howManyTimes : howManyTimes + 1;

        function step() {
            document.title = (document.title == original) ? newMsg : original;

            if (--howManyTimes > 0) {
                timeout = setTimeout(step, 1000);
            };
        };

        howManyTimes = parseInt(howManyTimes);

        cancelFlashTitle(timeout);
        step();
    };

    window.cancelFlashTitle = function () {
        clearTimeout(timeout);
        document.title = original;
    };

}());
flashTitle("New Notification");

EDIT - fixed small error