我希望一段代码仅在第一次运行后 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/