Sign in

JS / jQuery table total, how to optimize asynchronous request frequency too fast

Mladen edited in Fri, 24 Jun 2022

The project needs to dynamically list the reviewers according to the amount. When the amount changes, the asynchronous request is executed. The problem now is that whether I change the amount or the quantity, the amount will be calculated and the asynchronous request will be executed,


Change of unit price or quantity each time ( Calculate the total amount ) Will execute asynchronous request, it consumes resources


What's a good optimization plan?

This is the JS code:

    // 监听单价和数量的变化
    $(document).on('input propertychange', '.cg-items-table tbody input.listen', function (e) {
        var tr = $(this).parent().parent(),
            unitPrice = parseFloat(tr.find('td:nth-child(5) input').val()),
            quantity = parseFloat(tr.find('td:nth-child(6) input').val()),
            amount = ((unitPrice ? unitPrice : 0) * (quantity ? quantity : 1));
        tr.find('td:nth-child(8) input').val(amount.toFixed(2));
    // 计算合计金额并执行异步请求
    function amountCalculation() {
        var totalAmount = 0;
        // 填充行合计
        $('.cg-items-table tbody tr').each(function (index) {
            totalAmount += parseFloat($(this).find('.amount').val());
        // 总金额赋值
        $('.cg-items-table tfoot tr td:last-child input').val(totalAmount.toFixed(2));
            totalAmount: totalAmount
5 Replies
commented on Fri, 24 Jun 2022

To search the next function.

commented on Fri, 24 Jun 2022

If the total price is not changed, there is no need for asynchronous request. 2. If the total price is changed, the previous request is meaningless and cancelled directly. 3. Avoid changing too fast and keep sending, make a delay

commented on Fri, 24 Jun 2022

Check the anti chattering throttle function

commented on Sat, 25 Jun 2022

When the input is modified, the request is changed from listening to input property change to listening to blur

commented on Sat, 25 Jun 2022

Function anti shake and throttling

lock This question has been locked and the reply function has been disabled.