【发布时间】:2012-10-16 19:30:07
【问题描述】:
我一直无法处理时间事件。有人可以解释为什么A不起作用而B起作用吗?唯一的区别是在 A 中我将事件绑定放在了一个函数中。不用担心函数关闭,它与问题无关。测试A的时候没有js错误但是定时器没有清零。
A->
Test.Navigation = (function() {
var openTimer = null;
var closeTimer = null;
var addListeners = function() {
$('.hover_container').on('mousemove', function(e) {
clearTimeout(closeTimer);
});
$('.hover_container').on('mouseleave', function(e) {
// set the close timer
var container = this;
closeTimer = setTimeout(function() {
//has the mouse paused
close(container);
}, 750);
});
};
return {
init : function() {
addListeners();
}
};
})();
B->
Test.Navigation = (function() {
var openTimer = null;
var closeTimer = null;
$('.hover_container').on('mousemove', function(e) {
clearTimeout(closeTimer);
});
$('.hover_container').on('mouseleave', function(e) {
// set the close timer
var container = this;
closeTimer = setTimeout(function() {
//has the mouse paused
close(container);
}, 750);
});
var addListeners = function() {
// nothing here
};
return {
init : function() {
addListeners();
}
};
})();
编辑:请忽略容器部分,它与问题无关,它只是我没有取出的完整代码的一部分
【问题讨论】:
-
对单个计时实例使用
setTimeout。使用setInterval进行持久计时。 -
在容器的直接作用域中声明
var container = this;,而不是在另一个函数中。在 A 中,容器不是你需要的。 -
@dystroy 容器是我需要的,这不是问题所在,如果清除计时器工作,则关闭功能不会触发
标签: javascript jquery timer settimeout