清除超时不起作用

发布于 12-28 15:28 字数 525 浏览 1 评论 0原文

我正在尝试改进此插件,添加事件处理程序以在您播放/停止时切换幻灯片上的鼠标进入/鼠标离开。我见过很多人对js函数setTimeout和clearTimeout有同样的问题,我也遇到了麻烦。这就是我所拥有的

var autoplay;
container.mouseenter(function(){
    autoplay = setTimeout(function() {
        slide('next');
    }, config.auto);
    console.log('play');
}).mouseleave(function(){
    clearTimeout(autoplay);
    console.log('stop');

});

幻灯片开始在 mouseenter 中显示,但当我执行 mouseleave 时不要停止。我做错了什么?这是范围误解吗?我不知道我错过了什么。

I'm trying to improve this plugin adding events handlers to toggle play/stop when you mouseenter/mouseleave on a slide. I've seen loads of people having the same problem with the js function setTimeout and clearTimeout, and I'm having a trouble too. This is what I have

var autoplay;
container.mouseenter(function(){
    autoplay = setTimeout(function() {
        slide('next');
    }, config.auto);
    console.log('play');
}).mouseleave(function(){
    clearTimeout(autoplay);
    console.log('stop');

});

The slides start to show up in mouseenter, but don't stop when I do the mouseleave. What I am doing wrong? It is a scope misunderstanding? I don't know what I'm missing.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

放低过去2025-01-04 15:28:34

如果 container 中有完全一个匹配的元素(工作示例)。如果它有可能匹配多个元素,那么您将有多个元素共享同一个 autoplay 计时器句柄,并且它会变得有点混乱。如果是这样,请使用 data 将句柄实际存储在鼠标事件的元素上发生于:

container.mouseenter(function(){
    $(this).data("autoplay", setTimeout(function() {
        slide('next');
    }, config.auto));
    console.log('play');
}).mouseleave(function(){
    var autoplay = $(this).data("autoplay");
    if (autoplay) {
        clearTimeout(autoplay);
    }
    console.log('stop');
});

Live example

另外,可能值得清除autoplay(无论您将其存储在何处)它)当计时器触发时,所以你知道你没有待处理的计时器。

I can't see any reason why your code wouldn't work provided container has exactly one matched element in it (working example). If there's any chance that it may match more than one element, then you'll have multiple elements sharing the same autoplay timer handle and it'll become a bit of a mess. If so, use data to store the handle actually on the element the mouse event occurred on:

container.mouseenter(function(){
    $(this).data("autoplay", setTimeout(function() {
        slide('next');
    }, config.auto));
    console.log('play');
}).mouseleave(function(){
    var autoplay = $(this).data("autoplay");
    if (autoplay) {
        clearTimeout(autoplay);
    }
    console.log('stop');
});

Live example

Separately, it's probably worth clearing autoplay (wherever you store it) when the timer fires, so you know you don't have a pending timer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文