Search code examples
javascriptjqueryhtmltimer

variable set to true in setTimeout is always false?


Ok, I think I have a this context issue. I am trying to make, only on mousedown and the timer is reset on mouseup, a timer set in motion so that a boolean flag turns true after 5 seconds. If it is true when the timer is reset (on mouseup), a function this.triggerRoomChange() is triggered.

Here's what I have (its node):

   clearRoomChange(){

    this.readyToChangeRooms = true;
    console.log('READY');
  };

  onMouseDown()
  {

    this.mousedownTimeout = setTimeout(this.clearRoomChange, 5000);
    this.mouseDown++;
  }
  onMouseUp()
  {
    clearTimeout(this.mousedownTimeout);

    console.log(this.readyToChangeRooms);
    if(this.readyToChangeRooms)
    {
      this.triggerRoomChange();
      this.readyToChangeRooms = false;
    }
    this.mouseDown--;
  }

The print READY fires after the 5 seconds and the setTimeout appears to be cleared, however the variable (when printed on MouseUp) is always false. I clearly set it to true in this.clearRoomChange

Whats going on?


Solution

  • The timeout changes the scope. So you need to use bind to maintain scope

    this.mousedownTimeout = setTimeout(this.clearRoomChange.bind(this), 5000);