Detect how long an HTML button is pressed I recently had the need to detect how long a button is pressed and perform different actions based on that. I found some examples on Stack Overflow, but the ones I looked at showed how to use timeout().

I came up with this. There are probably other ways to solve this. While searching, I found an example using IIFE in JavaScript, which I then used for this tiny example.

HTML:

&lt;button id="button"&gt;click&lt;/button&gt;


JavaScript:

(function(window, document, undefined){
    'use strict';
    var start;
    var end;
    var delta;
    var button = document.getElementById("button");

    button.addEventListener("mousedown", function(){
        start = new Date();
    });

    button.addEventListener("mouseup", function() {
        end = new Date();
        delta = end - start;
        if (delta &gt; 0 &amp;&amp; delta &lt; 500) {
            alert("less than half second:");
        }
        if (delta &gt; 1000) {
            alert("more than a second:");
        }
    });
})(window, document);
500 and 1000 should be constants.

Where you have them now you need to look through to find them in code when you want to change them. I know this is an example, but they're also meaningless. 500 doesn't tell you why half a second matters, but TIMEOUT tells you what the purpose of the number is. Declare your time values at the top of the function with clear names that denote what they're for.