Skip to content

Commit

Permalink
FIX: Clear last debounce timeout if componentDidUnmount - joshwnj#66
Browse files Browse the repository at this point in the history
  • Loading branch information
Radu-Sebastian Amarie committed Mar 8, 2017
1 parent de63e79 commit aacbb83
Showing 1 changed file with 17 additions and 14 deletions.
31 changes: 17 additions & 14 deletions visibility-sensor.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,6 @@ if (typeof window !== 'undefined') {
containmentPropType = React.PropTypes.instanceOf(window.Element);
}

function debounce(func, wait) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
func.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}

module.exports = React.createClass({
displayName: 'VisibilitySensor',

Expand Down Expand Up @@ -89,6 +76,21 @@ module.exports = React.createClass({
}
},

debounce: function (func, wait) {
var timeout;

return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
func.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
this.lastTimeout = timeout;
}.bind(this)
},

getContainer: function () {
return this.props.containment || window;
},
Expand All @@ -101,7 +103,7 @@ module.exports = React.createClass({
}

if (this.props.scrollCheck) {
this.debounceCheck = debounce(this.check, this.props.scrollDelay);
this.debounceCheck = this.debounce(this.check, this.props.scrollDelay);
this.getContainer().addEventListener('scroll', this.debounceCheck);
}

Expand All @@ -113,6 +115,7 @@ module.exports = React.createClass({
if (this.debounceCheck) {
this.getContainer().removeEventListener('scroll', this.debounceCheck);
this.debounceCheck = null;
clearTimeout(this.lastTimeout);
}
if (this.interval) { this.interval = clearInterval(this.interval); }
},
Expand Down

0 comments on commit aacbb83

Please sign in to comment.