我使用从vanilla js中可以找到的示例将它们放在一起,因为我无法准确找到我在p5中已经完成的需要。它正在做我想做的事情,这使我在mousePressed和mouseReleased之间有一段时间。问题:我的方法有效吗?阅读有关计时器的其他评论后正在寻找一些专家建议...不想在后台运行计时器,因为我没有正确处理它...let timeTaken = 0;let result = 0;let timer;function setup() { createCanvas(500,500);}function draw() { background('black'); fill('white'); textSize(15); text("timeTaken: "+timeTaken,20,20); textSize(60); text(result,100,100);}function mousePressed() { result = 0; timeTaken = 0; if (timer) { clearInterval(timer); } timer = setInterval(()=>{timeTaken++;}, 1);}function mouseReleased() { clearInterval(timer); result = timeTaken;} 最佳答案 您根本不需要计时器,这尤其重要,因为不能保证在您要求计时器被触发时将其触发。因此,如果您以1毫秒的间隔启动一个计时器,则在10毫秒内它可能仅被调用两次或三次,因此最终以2或3而不是10计数。(实际上,计时器,如果您安排一个1毫秒的回调,则在五个回调之后,浏览器应该限制它并使其至少等待4毫秒。¹)只需记录下mousedown的当前时间,然后从mouseup的当前时间中减去,就可以知道它停下来了多长时间(以毫秒为单位):let down;let timeTaken = 0;function mousePressed() { down = Date.now();}function mouseReleased() { timeTaken = Date.now() - down;}现场示例:let down;let timeTaken = 0;function mousePressed() { down = Date.now();}function mouseReleased() { timeTaken = Date.now() - down;}const target = document.getElementById("target");target.addEventListener("mousedown", mousePressed);target.addEventListener("mouseup", function() { mouseReleased(); console.log(`Time taken: ${timeTaken}ms`);});#target { user-select: none;}<div id="target">Click me<div>¹关于夹紧,您可以在这里看到它的作用:const now = typeof performance !== "undefined" && performance.now ? performance.now.bind(performance) : Date.now.bind(Date);let last = now();let counter = 0;const entries = [];const timer = setInterval(() => { const n = now(); entries.push(n - last); last = n; if (++counter > 15) { clearInterval(timer); for (const entry of entries) { console.log(entry + "ms"); } }}, 1);.as-console-wrapper { max-height: 100% !important;}关于javascript - 测量鼠标点击时间的计时器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56557493/ 10-10 00:12