Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: throttle keyboard input to improve responsiveness #287

Merged
merged 1 commit into from
Mar 12, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,
}