【问题标题】:setTimeout after clicks - how to get only last iteration点击后的 setTimeout - 如何仅获取最后一次迭代
【发布时间】:2018-01-13 14:32:25
【问题描述】:

Heloo,我已经厌倦了如何使用购物车上的产品计数器调用 ajax。

我在这里创建了一个简单的例子:https://jsfiddle.net/s77j79nn/7/

问题是当我想从数量“1”传递到数量前。 “7”我在文档窗口中收到 6 个警报,相当于 6 个 ajax 请求。我希望设置超时能解决这个问题,但没有。

我只想在 2-3 秒后获得最后一个数量变量,如果现场有人会检查从 1 到 8 的数量,他的浏览器只调用一个对数据库的请求。

有人可以解决我的问题吗?谢谢!

$(".iteration").on("click", function() {

  var quantity = $(".cart-product .counter-label").text(); 
  var pricee = $(".single-price").text();  

  if( $(this).hasClass("plus") ) {
    if ( quantity != 9 ) {
      quantity++;
      $(this).parent().find(".counter-label").text(quantity);

      setTimeout(function(){

        // CALL AJAX HERE

        $(".price-value").text((quantity * pricee).toFixed(2));
        alert(quantity);
      },2000);    
    }  
  }
  if( $(this).hasClass("minus") ) {
    if ( quantity != 1 ) {
        quantity--;
        $(this).parent().find(".counter-label").text(quantity);
    }
  } 
});

【问题讨论】:

    标签: jquery ajax settimeout


    【解决方案1】:

    您可以存储超时 ID,并在您再次按下加号按钮时取消它。像这样的:

    clearTimeout(timeout);  
    timeout = setTimeout(function(){...}, 2000);
    

    这是您的jsfiddle,包括上述更改。

    【讨论】:

      猜你喜欢
      • 2022-11-07
      • 2015-09-14
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 1970-01-01
      • 2011-01-17
      • 2016-05-10
      • 1970-01-01
      相关资源
      最近更新 更多