Search code examples
jqueryeventstimeexecute

Timing event execution using jquery


How can I time the execution of a JQuery function or event? I don't mean executing an event or function after a timeout. I want something like, capturing keyevents for (within) 20 seconds, not after 20 seconds. I have tried several ideas but not working the way I want.


Solution

  • You can use setInterval()

    Given the markup

    <p>Interval: <span id="interval"></span></p>
    <p>Counter: <span id="counter"></span></p>
    <button id="start">Start</button>
    

    You can do something like this to capture keyups for 20 sec

    $(function(){
        var counter = 0;
        $("#start").click(function(){
            counter=0;
            var startTime = new Date().getTime() / 1000;
    
            $("body").on("keyup", function(){
                counter++;
                $("#counter").text(counter);
            });
            var intId = setInterval(function(){
                currentTime = new Date().getTime() / 1000;
                timeInterval = currentTime - startTime;
                $("#interval").text(timeInterval);
                if (timeInterval >= 20) {
                    $("body").off("keyup");
                    clearInterval(intId);
                }
            },1000);
        });
    });
    

    Here is jsFiddle