Javascript功能:自上次尝试以来已经过了半秒钟?

heo*_*ing 3 javascript time timestamp overflow

我想构建一个函数,如果它在半秒钟之前被调用,则返回false.

timething.timechill=function(){
    var last
    if (last){
            if ((now.getTime()-last)>500){
                    return true
            }
            else{

                    return true
            }
    }
    else {
            last=now.getTime()
            return false
    }}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?我想避免使用setTimeout()并忽略输入,如果它太快以避免溢出.这是一个好习惯吗?

Jam*_* M. 5

timething.timechill = (function () {
    var lastCall = 0;
    return function () {
        if (new Date() - lastCall < 500)
            return false;
        lastCall = new Date();
        //do stuff
    }
})();
Run Code Online (Sandbox Code Playgroud)

这里的想法是(function() { ... })();创建一个匿名函数并立即运行它.timething.timechill未分配此功能.相反,它被赋予此函数返回的内部函数.

请注意,该内部函数lastCall未声明(使用var关键字).并且当外部函数返回时,lastCall不会消失,因为内部函数由于它引用变量而"封闭"它.

当您timething.timechill稍后运行并遇到此变量时,它将在函数的范围外搜索变量并找到之前声明的变量.当它返回时,变量仍然不会消失,因为它是在函数范围之外声明的.

很难清楚地解释这个概念,但它非常有用,因为lastCall其他代码看不到它们是不可见的.