Skip to content

Commit

Permalink
perf: throttle keyboard input to improve responsiveness
Browse files Browse the repository at this point in the history
  • Loading branch information
nolanlawson committed Mar 10, 2019
1 parent 8c80e7d commit 8f6145e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/components/search.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import PropTypes from 'prop-types'

import { search as icons } from '../svgs'
import NimbleEmojiIndex from '../utils/emoji-index/nimble-emoji-index'
import { throttleIdleTask } from '../utils/index'

export default class Search extends React.PureComponent {
constructor(props) {
Expand All @@ -15,9 +16,11 @@ export default class Search extends React.PureComponent {
this.data = props.data
this.emojiIndex = new NimbleEmojiIndex(this.data)
this.setRef = this.setRef.bind(this)
this.handleChange = this.handleChange.bind(this)
this.clear = this.clear.bind(this)
this.handleKeyUp = this.handleKeyUp.bind(this)

// throttle keyboard input so that typing isn't delayed
this.handleChange = throttleIdleTask(this.handleChange.bind(this))
}

search(value) {
Expand Down
19 changes: 19 additions & 0 deletions src/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,24 @@ function measureScrollbar() {
return scrollbarWidth
}

// Use requestIdleCallback() if available, else fall back to setTimeout().
// Throttle so as not to run too frequently.
function throttleIdleTask(func) {
const queue =
typeof requestIdleCallback === 'function' ? requestIdleCallback : setTimeout
const clear =
typeof cancelIdleCallback === 'function' ? cancelIdleCallback : clearTimeout

let id

return function throttled() {
if (id) {
clear(id)
}
id = queue(func)
}
}

export {
getData,
getSanitizedData,
Expand All @@ -197,4 +215,5 @@ export {
deepMerge,
unifiedToNative,
measureScrollbar,
throttleIdleTask,
}

0 comments on commit 8f6145e

Please sign in to comment.