要感谢this post找到了执行此操作的方法,但是如下面的代码所示,当自上次单击以来的时间大于2秒时,我正在尝试console.log('Done');
。但是,这不起作用。
var lastClick = 0;
var button_pressed = false;
let button1 = document.getElementById('button1');
let button2 = document.getElementById('button2');
button1.onclick = function() {
button_pressed = true;
CheckAnswer();
}
button2.onclick = function() {
button_pressed = true;
CheckAnswer();
}
function CheckAnswer() {
if(button_pressed === true) {
var d = new Date();
var t = d.getTime();
if(t - lastClick < 2000) {
console.log('Continue');
}
} else if (t - lastClick > 2000) {
console.log('Done');
}
lastClick = t;
}
<button id="button1">Button1</button>
<button id="button2">Button2</button>
谢谢您的帮助。
答案 0 :(得分:1)
如果代码要求button_pressed
为false
,则代码永远不会到达else
我已修复您的代码,请参见下文。
现在else if
和button_pressed === true
语句一起声明了。
function CheckAnswer() {
if(button_pressed === true) {
var d = new Date();
var t = d.getTime();
if(t - lastClick < 2000) {
console.log('Continue');
} else {
console.log('Done');
}
}
lastClick = t;
}
答案 1 :(得分:-1)
var lastClick = Date.now();
var button_pressed = false;
let button1 = document.getElementById('button1');
let button2 = document.getElementById('button2');
button1.onclick = function() {
button_pressed = true;
CheckAnswer();
}
button2.onclick = function() {
button_pressed = true;
CheckAnswer();
}
function CheckAnswer() {
var t = Date.now();
var diff = t - lastClick;
if(diff < 2000) {
console.log('Continue');
} else {
console.log('Done');
}
lastClick = t;
}
<button id="button1">Button1</button>
<button id="button2">Button2</button>