Javascript clearInterval not clearing

Javascript clearInterval not clearing

本文关键字:clearing not clearInterval Javascript      更新时间:2023-09-26

我有以下JS代码

$('body').on({
    click: function()
    {
        var el = $(this);
        lookUpTask(el);
        el.bind('blur', function(){
            timeOutTask = setInterval(function(){
                if( timeOutTask )
                {
                    clearInterval(timeOutTask);
                    el.trigger('remove_match');
                }
            }, 500);
            $('body').on({
                click: function(event)
                {
                    var match = $(this);
                    var color = match.attr('color');
                    // Check color to change brightness
                    var brightness = hexToLuminance(color);
                    var text_color = '#000';
                    if( brightness < 128 ) {
                        text_color = '#fff';
                    }
                    // Change color according to brightness
                    el.css('color',text_color);
                    el.parent().parent().children('.remove').css('color',text_color);
                    el.parent().parent().children('.resize').css('color',text_color);
                    // Change the background and task name
                    el.parent().parent().css('background-color', color);
                    el.val(match.html());
                    // Update DB

                    // Remove the task_match
                    el.trigger('remove_match');
                }
            },'.match');
        });
        el.bind('remove_match', function(){
            if( el.val == "" ) {
                el.val('Select Task');
            }
            el.css('text-align','center');
            el.parent().children('.match_results').remove();
            clearInterval(timeOutTask);
        });
    },
    keyup: function(event)
    {
        lookUpTask($(this));
    }
},'.task_select');

我想做的是,当用户单击.task_select时,我会显示匹配的结果并将其显示在屏幕上。现在,用户可以选择其中一个选项,也可以单击外部。如果在外部,则匹配的结果应该关闭。如果选择了其中一个选项,那么中间的整个代码都会运行。

问题是匹配的结果覆盖在另一个div上,如果点击它,就会发生其他事情。当我点击匹配的结果时,代码注册为点击外部(因此匹配的所选内容消失,效果就像我点击了我不想点击的另一个div。

所以我的解决方案是在点击外部之前放置一个计时器。这一切都很好,除了clearInterval没有清除计时器!!所以我第二次加载东西时,计时器好像没有被清除!

为什么?!

您正在用新的间隔覆盖timeOutTask。您可以将间隔缓存到一个数组中,类似于以下内容:

var timeOutTasks = [];
$('body').on({
    ...
    el.bind('blur', function(){
        timeOutTasks.push(setInterval(function(){
            clearInterval(timeOutTasks.pop());
                         ...
        }, 500);
            ...
    }
           ...
}