javascript:当在短时间内单击多个复选框时,如何延迟提交数据?

发布于 2024-09-03 07:28:51 字数 164 浏览 3 评论 0原文

我有一组复杂的动态 html 形式的复选框。每当用户单击一个复选框时,就会生成一个相当昂贵的查询并将其提交到远程服务器。 我想根据用户的下一步操作延迟此提交操作。如果用户快速单击多个复选框,则应丢弃所有第一次单击,仅处理最后一次单击,并最终在 1 秒左右后提交。 也许这是一个常见问题,但我以前从未处理过超时问题。

I have an array of checkboxes in a complex dynamic-html form. Whenever a user clicks one checkbox, a fairly expensive query is generated and submitted to a remote server.
I want to delay this submit action depending on the users next action. If the user clicks several checkboxes quickly, all of the first clicks should be discarded, only the last one is processed and eventually submitted after 1 second or so.
maybe this is a common problem but I have never worked with timeouts before.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岁月苍老的讽刺 2024-09-10 07:28:51

您尝试使用的方法称为去抖动。
我的 javascript 中通常有一个通用的去抖动函数:

var debounce=function(func, threshold, execAsap) {
    var timeout;
    return function debounced () {
        var obj = this, args = arguments;
        function delayed () {
            if (!execAsap)
                func.apply(obj, args);
            timeout = null; 
        };
        if (timeout)
            clearTimeout(timeout);
        else if (execAsap)
            func.apply(obj, args);
        timeout = setTimeout(delayed, threshold || 100); 
    }; 
};

然后当某些东西需要去抖动时,我通常会对该函数进行去抖动,
在您的情况下,它可能类似于:

$("checkbox").click(debounce(callBackFunction,1000));

其中 callbackFunction 是执行“昂贵的 jquery”的函数,1000 是超时。

应用上述内容意味着回调函数会在 1 秒超时后被调用,如果以任何更短的间隔调用,则该调用将被忽略。

the method you are trying to employ is called debouncing.
I usually have a generic debounce function in my javascript:

var debounce=function(func, threshold, execAsap) {
    var timeout;
    return function debounced () {
        var obj = this, args = arguments;
        function delayed () {
            if (!execAsap)
                func.apply(obj, args);
            timeout = null; 
        };
        if (timeout)
            clearTimeout(timeout);
        else if (execAsap)
            func.apply(obj, args);
        timeout = setTimeout(delayed, threshold || 100); 
    }; 
};

And then when something needs debouncing, I usually debounce the function,
In your case it might be something like:

$("checkbox").click(debounce(callBackFunction,1000));

where callbackFunction is the function that does your "expensive jquery" and 1000 is the timeout.

Applying the above would mean that callbackFunction is called at 1 second timeouts, if it is called at any shorter intervals, the call is ignored.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文