Home > Software engineering >  When I type to fast on input it renders the wrong div
When I type to fast on input it renders the wrong div

Time:05-17

I'm have to show two different dropdown in my input. I'm doing it by having an shouldShowWarningBox method that it's called every time the input is updated by the user an updates the value of showWarningBox. The point is, when I type to fast I receive a false showing the warning message, but it's not true. If I type slowly the first div is rendered.

I've tried with and without the debounce function, but the behavior is the same, just with a little delay.

Any ideas?

.html

<div v-if="!showWarningBox">
 //dropbox
</div>

<div v-if="showWarningBox">
 //warning message
</div>

.js

data () {
 return {
  showWarningBox: false,
 }
},
methods: {
 onInput (value) {
  this.debounce(this.shouldShowWarningBox(), 1000)
 },
 shouldShowWarningBox () {
  //conditional that changes showWarningBox
 },
 debounce (func, delay) {
  let id
 
  return (...args) => {
   if (id) clearTimeout(id)

   id = setTimeout(() => {
    func(...args)
   }, delay)
  }
 },
}

CodePudding user response:

debounce returns a "debounced" function. You should save that function in a component property and call that debounced function on input:

data(){
  let debouncedFn = this.debounce(this.shouldShowWarningBox, 1000)
  return {
    debouncedInput: debouncedFn
  }
},
methods: {
 onInput (value) {
  this.debouncedInput()
 },
 //...
}
  • Related