简体   繁体   English

如何在 function 调用中实现去抖动 javascript

[英]How to implement debounce in function call in javascript

I asked a question How to fire Ajax request after user inactivity in 1.5 seconds on how to update user data after user has finished typing instead on every key up, the I was referred to a post where they recommended using javascript debounce, which I love How to implement debounce fn into jQuery keyup event?我问了一个问题How to fire Ajax request after user inactivity in 1.5 seconds on how to update user data after user are done typing in instead on each key up,我被提到了一篇他们推荐使用javascript debounce的帖子,我喜欢How在 jQuery keyup 事件中实现 debounce fn? but I can't seem to find a way to implement it into my code, this is what the solution I was referred to said I should do但我似乎找不到将它实现到我的代码中的方法,这就是我提到的解决方案所说的我应该做的

 $('input').keyup(debounce(function(){
 var $this=$(this);
 //alert( $this.val() );
 var n1 = $this.val();
 var n2 = $('#n2').val();
 var n3 = $('#n3').val();
 var calc = n1 * n2 * n3;
 alert(calc);
 },500));

my function works perfectly but I dont want it running every time, so I don't know how to implement debounce in this case, this is the code that I want to add debounce to我的 function 工作得很好,但我不希望它每次都运行,所以我不知道在这种情况下如何实现去抖动,这是我想添加去抖动的代码

//cart.php //cart.php

<input type="text" class="count_cart content_to_cart oninput qty-remove-defaults" onkeyup="setcart(this)" onkeydown="autoSave(this)" id="updates_486" >

function autoSave(e){ //JS where I want to implement debounce    
setTimeout(function(){
var getsizes_response = $(e).attr("id");
var getsave_response_quantity = $("#"+getsizes_response).val();
$.ajax({
type: "POST",
url: "functions.php",
data: {getsizes_response: getsizes_response, getsave_response_quantity: getsave_response_quantity},
cache: false,
timeout: 5000,
success: function(r){   
$("#ajax_responses_get_positioner").show(); 
$("#ajax_responses_get_positioner").html(r);
},
error: function(){      
$("#ajax_responses_get_positioner").show(); 
$("#ajax_responses_get").html("Error saving order, please reload page and try again."); 
$("#ajax_responses_get").css({'background': 'red', 'display': 'block'});
$("#ajax_responses_get_positioner").delay(6000).fadeOut("fast");
}
}); 
}, 1500);   
} 

Debounce takes a function as an argument, and returns a function (the debounced version of the original function). Debounce 将 function 作为参数,并返回 function(原始函数的去抖版本)。 Functions that do this are called "higher order functions".执行此操作的函数称为“高阶函数”。 In the first example, the function isn't named, and it is passed directly to debounce as soon as it is created.在第一个示例中,function 没有命名,它一创建就直接传递给 debounce。 In the second example, you've named the function autosave (which is a great thing to do), but it doesn't make it any harder.在第二个示例中,您将autosave命名为 function(这是一件好事),但这并没有让它变得更难。 All you have to do is call debounce before using your function name .您所要做的就是在使用您的 function名称之前调用 debounce 。 So when you use it on keyup :因此,当您在keyup上使用它时:

$('input').keyup(debounce(autoSave, 500))

If you wanted to always debounce autosave, you could save the debounced function to the variable autoSave, so after that point, it is always debounced.如果你想总是去抖动自动保存,你可以将去抖动的 function 保存到变量 autoSave,所以在那之后,它总是去抖动的。 (Or you could use a different name - up to you). (或者您可以使用不同的名称 - 由您决定)。

autoSave = debounce(autoSave, 500)

$('input').keyup(autoSave)

Re-assigning a decorated function to the original function name is called "decorating", and the higher order function is called the decorator.将一个修饰的 function 重新分配给原来的 function 名称称为“装饰”,更高阶的 function 称为装饰器。 Some languages provide a special syntax for this, and javascript is considering adding one as well:一些语言为此提供了特殊的语法,javascript 也在考虑添加一个

@debounce(500)
function autoSave() { … }

That would do the same as the previous example: call debounce with autoSave and then assign it to autoSave .这将与前面的示例相同:使用autoSave调用 debounce ,然后将其分配给autoSave However, if you want to do that today, you need to use babel or typescript and the right plugins.但是,如果你今天想这样做,你需要使用 babel 或 typescript 和正确的插件。

After help from garrett motzner, I figured it out.在 garrett motzner 的帮助下,我想通了。

<input type="text" class="count_cart autow content_to_cart oninput qty-remove-defaults" onkeyup="setcart(this)" id="updates_486" >

$('.autow').keydown(debounce(function(){
var qthis=$(this);  
var getsizes_response = $(qthis).attr("id");
var getsave_response_quantity = $("#"+getsizes_response).val();
$.ajax({
type: "POST",
url: "functions.php",
data: {getsizes_response: getsizes_response, getsave_response_quantity: getsave_response_quantity},
cache: false,
timeout: 5000,
success: function(r){   
$("#ajax_responses_get_positioner").show(); 
$("#ajax_responses_get_positioner").html(r);
},
error: function(){      
$("#ajax_responses_get_positioner").show(); 
$("#ajax_responses_get").html("Error saving order, please reload page and try again."); 
$("#ajax_responses_get").css({'background': 'red', 'display': 'block'});
$("#ajax_responses_get_positioner").delay(6000).fadeOut("fast");
}
});
},500));

function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};

This allows it to call only once, after user finish typing.这允许它在用户完成输入后只调用一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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