perf: throttle keyboard input to improve responsiveness

release
Nolan Lawson 2019-03-10 09:40:59 -07:00
parent 8c80e7d4e5
commit 8f6145e383
2 changed files with 23 additions and 1 deletions

View File

@ -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) {
@ -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) {

View File

@ -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,
@ -197,4 +215,5 @@ export {
deepMerge,
unifiedToNative,
measureScrollbar,
throttleIdleTask,
}