Two dom events that call the same function should call the function only once if it happens at the same time

I have one input and one button. When I erase the input and the input has changed, the price () function should be called. Also, when I click the button, the price () function is called.

The problem is that when the user changes the input value and presses the button, the price () function is called twice. I do not want this to happen.

I tried the old-fashioned way by setting the variable "inPriceFunction" to true when entering and checking to see if it was set before entering. This did not work, because two events (blur and click) are executed at the same time, there was no time for the if and variable parameters.

How can i avoid this?

What I tried:

<div> <input type=text onchange="price();" /> </div> <button onclick="price();" />test</button> <script> called = 0; function price() { if(called == true){ return; } else { called = true; } console.log("called"); called=false; } </script> 
+6
source share
5 answers

A click and change event does not occur at the same time. They occur one after another.

  • First, the "change" event occurs, setting called = true , then executing console.log("called"); and setting called=false again.
  • Then the click event is fired, but called == false , so it sets called = true; , and then does console.log("called"); and sets called=false again.
+1
source

Underlined: http://underscorejs.org/#throttle

  • throttle will prevent your function from being called twice within the specified time period.
  • once will prevent your function from being called twice.
+3
source

Here's the jsfiddle that will do the job. Of course, you should not use global variables:

http://jsfiddle.net/SZe26/

 var clicktimer = null; function clickfunc() { var BLOCK_TIME = 500; function handleclick() { console.log("Pressed!"); } if (clicktimer) { console.log("Skipping handling of click!"); } else { handleclick(); clicktimer = setTimeout(function() { clicktimer = null; }, BLOCK_TIME); } } 
+1
source

add timeout, something like this

 function schedludePrice() { if(myTimeOut){ clearTimeout(myTimeOut); } myTimeOut = setTimeout('price()', 10); } 

thus, if a function is called twice in a short time by your blur and click event, the Price function will be called only once.

0
source

The easiest way to handle this may be to store the date-time when the price is being called, and use it to check if it is called too recently.

 if (refDate > new Date(10000 + (new Date())) { // 1 second delay? return; } refDate = new Date(); 

It is likely that two calls to Date will return the same date (so no date manipulation is required).

0
source

Source: https://habr.com/ru/post/945264/


All Articles