简体   繁体   中英

jquery onchange set timeout

I want certain code to fire when user change a quantity in a input field. but when user use the little up and down arrow to increase and decrease the quantity quickly. Like press it 5 time to get to 5. I dont want the code to fire 5 times. So I want to set a timer. When on change event is detected it will wait for 1 sec or wait until the on change has stopped. Then grab the latest value.

So is there a way to detect multiple changes in short time span and no nothing. Then if the change happen and no more change happen after x amount to time. do something.

$("#quantity").on('change',function(){
    setTimeout(function(){ 
        console.log("fired");
    }, 1000);
});

My code is just delaying the fired.

So how can we accomplish this.

Found duplicated question with answer here Jquery change with delay

Here's what I've done on input boxes to prevent triggering frequent changes while user is typing:

         var timeoutId = 0;    
         object.dom.input.addEventListener('input',function() {
            clearTimeout(timeoutId);
            // do stuff
            // Fire our onchange event
                if (this.delayOnChange > 0) {
                    timeoutId = setTimeout(function() { this.onchange() }, this.delayOnChange);
                } else {
                    this.onchange();
                }
            }
        },false);

This checks to see if we have set a 'delayOnchange', and if we have delay the trigger of an 'onchange()' event. We reset the timer (clearTimeout()) each time a change is made to the input so we are basically waiting for the user to stop fast typing before triggering the onchange.

The code below will delay the work until 3 seconds have passed since the last 'input' event. It does this by cancelling the previous timeout (via clearTimeout ) if another 'input' event occurs before the timeout executes its function.

 let time = 0;

 // On change paste keyup.
 $('#address_1').on('input', function () {
     // Reset the timer
     clearTimeout(time);

     time = setTimeout(function() {
         // enter code here or a execute function.
         doGeocode();
     }, 3000);
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM