Chris
Chris

Reputation: 59511

Set a minimum execution time for onMouseDown

I have the following popup window in my application which utilizes Bootstrap Tabs:

enter image description here

The Feedback tab has several sub-tabs and I have added functionality so that you can scroll between the overflowing sub-tabs (left and right). Here's how I've implemented that functionality (ReactJS):

this.feedbackScrollInterval = -1;    

_feedbackScroll = (id) => {
  let obj = ReactDOM.findDOMNode(this.refs.feedbackNav);
  let scrollWidth = obj.firstChild.scrollWidth;
  let offsetWidth = obj.firstChild.offsetWidth;
  if(this.feedbackScrollInterval==-1) {
    this.feedbackScrollInterval = setInterval(function(){
      if(id==1) {
        obj.firstChild.scrollLeft -= 5;
      } else {
        obj.firstChild.scrollLeft += 5;
      }
    }, 15);
  }
}

_clearFeedbackScroll = () => {
  clearInterval(this.feedbackScrollInterval);
  this.feedbackScrollInterval = -1;
}

and the markup for the buttons:

<Button onMouseDown={this._feedbackScroll.bind(this, 1)} onMouseUp={this._clearFeedbackScroll}><Glyphicon glyph="chevron-left"></Glyphicon></Button>
<Button onMouseDown={this._feedbackScroll.bind(this, 2)} onMouseUp={this._clearFeedbackScroll}><Glyphicon glyph="chevron-right"></Glyphicon></Button>

The above works as intended, but I want to add a minimum scroll time. For example, if I want a minimum scroll time of 250ms and the mouseUp event triggers after 150ms, I want the scroll to continue for another 100ms, until the minimum has been met.

How can this be implemented? (no jQuery)

Upvotes: 0

Views: 84

Answers (1)

Dan Prince
Dan Prince

Reputation: 29989

Keep a record of the time each time you start the scroll action.

this.scrollStarted = Date.now();

Then when the scroll finishes, check the duration.

let scrollFinished = Date.now();
let duration = scrollFinished - this.scrollStarted;

If the duration is greater than your threshold (250), then you can clear the interval. Otherwise, use setTimeout to appropriately delay the cancellation.

if(duration > 250) {
  // go ahead and cancel the scroll
} else {
  setTimeout(this._clearFeedbackScroll, 250 - duration);
}

Upvotes: 1

Related Questions