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

时间:2014-06-17 23:52:40

标签: javascript

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

我正在考虑这样做:

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

有更好的方法吗?

2 个答案:

答案 0 :(得分: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...

    }
}

答案 1 :(得分:2)

是的,您可以在页面加载时启动计时器,然后在六秒钟后执行某些操作:

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
    }
});

现在,当你开始时,计时器取决于你。上面的代码在代码运行时立即启动。如果代码位于script end body元素中(就在关闭</body>标记之前),这是最合适的,这是最佳实践。但是你需要在适合你的用例时启动计时器。