根据首次运行的时间执行不同的功能

wor*_*ith 0 javascript

我想要一段代码只有在第一次运行后的6秒内运行时才能执行.

我正在考虑这样做:

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

有一个更好的方法吗?

Kir*_*ice 6

或者,不使用计时器,只需跟踪它何时被调用:

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...

    }
}
Run Code Online (Sandbox Code Playgroud)