wordSmith
wordSmith

Reputation: 3183

Execute a function differently depending on when it was first run

I want a piece of code to execute only if run within a 6 seconds period after the first time it is run.

I was thinking about doing this like so:

var withinSix = false;
function onDeleteKeyUp(){
    withinSix = true;
    if(withinSix){
        //interaction code here
        setTimeout(function(){
            withinSix = false;
        }, 6000);
     }
});

Is there a better way to do this?

Upvotes: 0

Views: 53

Answers (2)

K893824
K893824

Reputation: 1319

Alternatively, without using an timers, just track when it is first called:

var called = -1;

function onDeleteKeyUp(){

    // Track the current time on the first call. (in ms)
    if (called === -1){
        called = (new Date()).getTime();
    }

    // Compare the current time to the time of the first call. (6s = 6000ms)
    if ((new Date()).getTime() - called < 6000){
        // Within 6 seconds...

    } else {
        // After 6 seconds...

    }
}

Upvotes: 6

T.J. Crowder
T.J. Crowder

Reputation: 1074979

Yes, you can start a timer when the page loads and then do something after six seconds:

var withinSix = true;   // By default, the click happened within six seconds
setTimeout(function() { // Start a timer that will fire after six seconds
    withinSix = false;  // The timer fired, clear the flag
}, 6000);               // 6000ms = 6 seconds
function onDeleteKeyUp(){
    if(withinSix){      // Was it before the timer fired?
        // Yes, it happened within 6 seconds of when this code started
    }
});

Now, when you start the timer is up to you. The above code starts it immediately when the code is run. This would be most appropriate if the code is in a script element at the very end of the body (just before the closing </body> tag), which is best practice. But you'll want to start the timer whenever is appropriate to your use case.

Upvotes: 2

Related Questions