javascript - 根据首次运行的时间以不同方式执行函数

标签 javascript

我希望一段代码仅在第一次运行后 6 秒内运行才执行。

我正在考虑这样做:

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

有更好的方法吗?

最佳答案

或者,不使用计时器,只跟踪第一次调用的时间:

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

    }
}

关于javascript - 根据首次运行的时间以不同方式执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24275058/

相关文章:

javascript - 遍历 ES6 类的方法和属性

javascript - jQuery 对象通过键获取值

javascript - if循环不跳转到else

javascript - 如何滚动到我的按钮? .scrollTo() 不起作用

javascript - 下拉列表中的 Angular 数据未第二次设置

javascript - 简单的 AJAX 脚本不会仅在主页上加载

javascript - 具有多种形式的 jQuery 序列化函数

javascript - 当从不同系统/浏览器同时调用同步方法时,两条记录会插入数据库中

javascript - 处理选择标记之间的交集

javascript - 为什么我的对象没有在 Angular View 中更新?