JS的clearartimeout即使在函数外部设置var也无法工作

JS clearTimeout fails to work even with var set outside the function

本文关键字:var 设置 工作 外部 函数 clearartimeout JS      更新时间:2023-09-26

我试图得到一个预览显示在悬停,但如果我移动我的鼠标离开,我希望预览不显示。目前,如果我快速移动鼠标越过"。searchRecord"元素,无论如何它都会在300ms后显示,并且由于在setTimeout函数完成之前调用了鼠标关闭函数而被"卡住"。如果我让光标停留在元素上,直到预览显示,一切都正常。

我在函数外设置了变量,就像我在其他地方读的那样,但是,它不会重置。我有点难倒了。

var timer;
$('.searchRecord').hover(function() {
    $(this).children('.previewLoad').show();
    var current = '#'+$(this).children('div').attr('id');
    //slight delay before hover so they can select what they want
    var timer = window.setTimeout(function(){
        $(current).fadeIn('fast');
        $(current).siblings('.previewLoad').hide();
    }, 300);
}, function() {
    window.clearTimeout(timer);
    var current = '#'+$(this).children('div').attr('id');
    previewTimeouter(current);
});

你有重复的定时器声明。删除悬浮回调中var timer中的var

var timer;
$('.searchRecord').hover(function() {
    $(this).children('.previewLoad').show();
    var current = '#'+$(this).children('div').attr('id');
    //slight delay before hover so they can select what they want
    timer = window.setTimeout(function(){
        $(current).fadeIn('fast');
        $(current).siblings('.previewLoad').hide();
    }, 300);
}, function() {
    window.clearTimeout(timer);
    var current = '#'+$(this).children('div').attr('id');
    previewTimeouter(current);
});

您在hover回调中再次使用var timer,该回调将其范围扩展到该函数并遮蔽父timer变量。

去掉内部的var,一切都会好起来的。