首页 > 解决方案 > 如何使 clearTimeout 着火

问题描述

我有一个<uses>没有的 SVG,当你触摸其中一个时,会触发一个touchstart事件。如果他们移动一个touchmove有计时器的事件触发。在touchend值应该改变之前,定时器被清除。但是,它无论如何都会改变。

这样做的结果是即使在被触发之后IsDraggingUnit也会设置为。我用 an 进行了测试,当您结束对元素的触摸时它成功触发。truetouchendalert

var IsDraggingUnit = false;
var timeOutClear;

$('#Selected_Items use').on("touchstart", function(event) {
  IsDraggingUnit = false;
  $('#test > p').text(IsDraggingUnit);

  $(this).on("touchmove", function(event) {
    timeOutClear = setTimeout(function() {
      IsDraggingUnit = true;
      $('#test > p').text(IsDraggingUnit);
    }, 500);
  });

  $(this).on("touchend", function(event) {
    clearTimeout(timeOutClear);
    if (IsDraggingUnit == false) {
      fnPlotShow($(this), bookingRental, bookingExists)
    }
  });
});

标签: javascriptjquery

解决方案


问题是因为您将touchmoveandtouchend事件嵌套在touchstart事件中。因此,在随后的touchstart事件中,每个事件都会触发多次,并且对原始超时的引用会丢失并且clearTimeout()不会全部清除。

要解决此问题,请不要将事件处理程序嵌套,并且不要忘记重新设置isDraggingUnitfalseontouchend

var isDraggingUnit = false, timeOutReference;

$('#Selected_Items use').on({
  touchstart: function(event) {
    isDraggingUnit = false;
    $('#test > p').text(isDraggingUnit);
  },
  touchmove: function(event) {
    timeOutReference = setTimeout(function() {
      isDraggingUnit = true;
      $('#test > p').text(isDraggingUnit);
    }, 500);
  },
  touchend: function(event) {
    clearTimeout(timeOutReference);
    if (!isDraggingUnit) {
      fnPlotShow($(this), bookingRental, bookingExists)
    }
    isDraggingUnit = false;
  }
});

另请注意,您的问题指出 SVG 包含<uses>节点,但您选择use. 不过,我认为这只是问题中的一个错字,因为如果那里存在不匹配,它将根本不起作用。


推荐阅读