Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two dom events that call the same function should call the function only once if happening in the same time

Tags:

javascript

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

The problem is that when a user modifies the value of the input and clicks the button, the price() function is called twice. I don't want this to happen.

I tried the old-fashioned way, setting a variable "inPriceFunction" to true while entering and checking if it is not set before entering. This didn't worked because the two events (blur and click) are executed in the exact same time, the if and the variable set didn't had the time to occur.

How can I avoid that?

What I have 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>
like image 736
Octavian Avatar asked May 17 '13 12:05

Octavian


3 Answers

Underscore has you covered: http://underscorejs.org/#throttle

  • throttle will prevent your function being called twice within a specified length of time.
  • once will prevent your function being called twice at all.
like image 72
Matthew Gilliard Avatar answered Sep 29 '22 08:09

Matthew Gilliard


The click and change event do not happen at the same time. They happen one after another.

  • First, the "change" event is fired, setting called = true, then execute console.log("called"); and set called=false again.
  • Then, the "click" event is fired, but called == false, so it sets called = true; and then execute console.log("called"); and set called=false again.
like image 35
Khanh TO Avatar answered Sep 29 '22 09:09

Khanh TO


Here's a jsfiddle that will do the job. You shouldn't use global variables, of course:

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);
    }
}
like image 35
Chris Avatar answered Sep 29 '22 08:09

Chris