javascript - 如何使 clearTimeout 着火
问题描述
我有一个<uses>
没有的 SVG,当你触摸其中一个时,会触发一个touchstart
事件。如果他们移动一个touchmove
有计时器的事件触发。在touchend
值应该改变之前,定时器被清除。但是,它无论如何都会改变。
这样做的结果是即使在被触发之后IsDraggingUnit
也会设置为。我用 an 进行了测试,当您结束对元素的触摸时它成功触发。true
touchend
alert
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)
}
});
});
解决方案
问题是因为您将touchmove
andtouchend
事件嵌套在touchstart
事件中。因此,在随后的touchstart
事件中,每个事件都会触发多次,并且对原始超时的引用会丢失并且clearTimeout()
不会全部清除。
要解决此问题,请不要将事件处理程序嵌套,并且不要忘记重新设置isDraggingUnit
为false
ontouchend
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
. 不过,我认为这只是问题中的一个错字,因为如果那里存在不匹配,它将根本不起作用。
推荐阅读
- html - Angular 10 中的动态绑定 HTML 控件
- javascript - 杀死Angular中的所有setInterval
- optimization - 运算符不适用于 dvar float+ * float[][range]
- ios - 如何在 Firebase IOS 中查看事件日志?
- html - 具有透明背景的按钮的多边形边框
- python - 使用 Python 重塑 CSV 行和列
- android - 如何从 arduino 获取蓝牙数据到移动应用程序?
- tkinter - TKINTER - 为什么窗口是黑色的
- javascript - 带地址栏的 1080px 高度发布
- reactjs - 如何为我的 React 应用启用多阶段构建