最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Lodash debounce firing every change - Stack Overflow

programmeradmin2浏览0评论

I'm trying to debounce sending a Redux Action from an input change in React.

const debouncedSubmit = debounce(() => dispatch(new TaskAnswerSubmit({index: props.index, text: answer})), 1000)

function onChange(e){
    setAnswer(e.target.value)
    debouncedSubmit()
}

This is delaying sending the actions, but still sending one for every keypress. I want to wait a second after the typing finishes before sending the action just once.

What am I doing wrong here?

I'm trying to debounce sending a Redux Action from an input change in React.

const debouncedSubmit = debounce(() => dispatch(new TaskAnswerSubmit({index: props.index, text: answer})), 1000)

function onChange(e){
    setAnswer(e.target.value)
    debouncedSubmit()
}

This is delaying sending the actions, but still sending one for every keypress. I want to wait a second after the typing finishes before sending the action just once.

What am I doing wrong here?

Share Improve this question asked Mar 3, 2020 at 23:48 beekbeek 3,7469 gold badges40 silver badges100 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 11

I believe what's happening here is that each key press causes a re-render, and during each render it's creating a new debouncedSubmit function, and each of those is firing. Try using React's useCallback method to memoize the function so it's not recreated on re-renders:

const debouncedSubmit = useCallback(debounce(() => dispatch(new TaskAnswerSubmit({index: props.index, text: answer})), 1000), []);

I think you need to throttle.

This is an answer from a previously asked question about the difference between throttle and debounce Difference Between throttling and debouncing a function:

Throttling will delay executing a function. It will reduce the notifications of an event that fires multiple times.

Debouncing will bunch a series of sequential calls to a function into a single call to that function. It ensures that one notification is made for an event that fires multiple times.

发布评论

评论列表(0)

  1. 暂无评论