Prototype.js 如何修复 clearTimeout( ) 的使用

Prototype.js how to fix use of clearTimeout( )

当用户将鼠标悬停在某些列表项上时,我正在使用 Prototype.js 加载 html 元素。我使用 setTimeout() 仅当鼠标在给定时间后仍在列表项上时才加载内容。当用户对同一列表项执行鼠标移出时,我想使用 clearTimeout。

clearTimeout() 没有清除我的超时。我很确定这是因为我对 Prototype.js

不熟悉而隐藏了一个常见的变量范围问题

有人可以指出此代码中的缺陷或确定我需要添加什么以使 clearTimeout() 函数正常工作吗?

document.observe( 'dom:loaded', function() {
var timeout;

$$('.nav-primary li.category').each( function( item ) {
    item.observe('mouseover', function(event) {
        event.stopPropagation();
        categoryId = event.currentTarget.id;
        getCategoryBlurb(categoryId);
        timeout = setTimeout( function() {
            showCategoryInfo(categoryData, categoryId);
        }, waitTime);
    });

    item.observe('mouseout', function(event) {
            event.stopPropagation();
            clearTimeout(timeout);
    });
    });
});

更新代码

$$('.nav-primary li.category').each( function( item ) {
    var timeout = null;

    item.observe('mouseover', function(event) {
        event.stopPropagation();
        categoryId = event.currentTarget.id;
        getCategoryBlurb(categoryId);
        if( timeout === null ) {
            timeout = setTimeout( function() {
                showCategoryInfo(categoryData, categoryId);
            }, waitTime);
        }
        console.log(timeout);
    });

    item.observe('mouseout', function(event) {
            if( timeout !== null ) {
                console.log(timeout);
                clearTimeout(timeout);
                timeout = null;
            }
    });

});

在设置之前清除超时

if (timeout) { clearTimeout(timeout); }
timeout = setTimeout( function() { /* code here */ });