Timothy's Dev Stuff

A collection of code snippets and other developer things.

A Simple Javascript Notification with Dynamic Timing

The need, or want, for this feature came up when I was working on something where I was using a bookmarklet to do things on a page and I wanted some form of visual indicator that things were happening as intended – without having to open the JS console on the page. This function will accept a string as an argument. Inside the function, it builds an element that will display on the page for a certain amount of time before it disappears. To calculate the display time, it assumes a reading speed of 200 words per minute but that can be changed by passing a number as a second argument. It then runs an anonymous function that counts the words in the passed message and creates a time to be used on the timeout function. The minimum amount of time is set by the Math.max() function.
function showNotification(message, avgReadingSpeed = 200) {
        let notification = document.createElement("div");
        notification.innerText = message;
        notification.style.position = "fixed";
        notification.style.top = "10px";
        notification.style.left = "10px";
        notification.style.backgroundColor = "rgba(0, 0, 0, 0.7)";
        notification.style.color = "white";
        notification.style.padding = "10px";
        notification.style.borderRadius = "5px";
        notification.style.zIndex = "10000";
        notification.style.maxWidth = "90vw";
        document.body.appendChild(notification);

        let time = (function() {
            let wordCount = message.trim().split(/\s+/).length;
            let readingTimeMillis = (wordCount / avgReadingSpeed) * 60 * 1000;
            return Math.max(readingTimeMillis, 3000);
        })();
        
        setTimeout(function() {
            document.body.removeChild(notification);
        }, time);
    }

One thing to keep in mind with this function is that it does not check whether there is a notification already showing – so there is no graceful handling of stacking although that could be pretty easily implemented.