Modern Front-End Development for Rails, Second Edition - incorrect code? (page 170)

I’m looking at the code for “Debouncing User Input” and the submit function appears to be wrong.

submit(): void {

If I’m reading the code properly, this.debounce is a function makes debounced version of the function given. (Effectively storing the state on the function itself.) For this to work, there must be a single instance. The code in this.submit creates a new instance each time it is called, meaning there is no shared state.

Wouldn’t the correct code be:

submit = this.debounce(this.basicSubmit.bind(this))

Thanks for the comment!

I went back and checked, and I do think you are right (the code as written does the first delay, which makes it look like its working), but it doesn’t properly end the timeout because, as you note, the timeoutId is not shared, so it submits the end state of the code multiple times.

This is a bug that has been in the code since the first edition and nobody caught it.

This will be fixed in the next beta.