Search code examples
javascriptcocos2d-iphonecocos2d-html5

What is the better way to get mouse hold time?


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);
        }
    }

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?


Solution

  • 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.

    Code is:

    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
        });
    }