获得鼠标保持时间的更好方法是什么? [英] What is the better way to get mouse hold time?

查看:112
本文介绍了获得鼠标保持时间的更好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算玩家按住鼠标按钮的时间.我试过了,但是没用:

I'm trying to count the time that player is holding the mouse button down. I tried this but it didn't works:

var Game = cc.Layer.extend({
    count: false,
    countTimer: null,

    init: function () {
        var selfPointer = this;

        this.canvas.addEventListener('mousedown', function(evt) {
            selfPointer.count = true;
            selfPointer.countTimer = window.setTimeout(selfPointer.Count(), 1);
        });

        this.canvas.addEventListener('mouseup', function(evt) {
            selfPointer.count= false;
            window.clearTimeout(selfPointer.countTimer);
        });
    },

    Count: function() {
        if (this.count)
        {
            window.setTimeout(this.Count(), 1);
        }
    }

这是我代码的一部分(为简洁起见),如果玩家按住按钮,我希望每1毫秒执行一次操作.

This is a part of my code(for brevity) that I want to do an action any 1 milisecond if player is holding the button.

此外,这是行不通的,我想这是比我的方法更好的方法.有什么想法吗?

This isn't working besides, I presume that is a better way to do this than mine way. Any ideas?

推荐答案

为什么您将超时用于此简单任务?您可以只获取鼠标按下的时间,鼠标按下的时间并计算它们之间的差异.无论如何,浏览器中的计时器分辨率小于1毫秒.阅读Nickolas Zakas的这篇文章以获得有关时间分辨率的更多信息.

Why do you use timeouts for this simple task? You can just get time of mousedown, time of mouseup and calculate difference of them. Anyway, timer resolution in browsers is less than 1ms. Read this article of Nickolas Zakas to get more info about time resolution.

代码是:

var Game = cc.Layer.extend({
  init: function () {
    var holdStart = null,
        holdTime = null;

    this.canvas.addEventListener('mousedown', function(evt) {
      holdStart = Date.now()
    });

    this.canvas.addEventListener('mouseup', function(evt) {
      holdTime = Date.now() - holdStart;
      // now in holdTime you have time in milliseconds
    });
}

这篇关于获得鼠标保持时间的更好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆