Javascript clearInterval()未清除间隔

Javascript clearInterval()未清除间隔,javascript,jquery,Javascript,Jquery,我试图在单击按钮时清除间隔,但它并没有清除间隔,因为我也尝试过使用全局范围。以下是设置间隔的函数: /* call idle js */ var awayCallback = function () { window.userLog = new Date().getTime(); CheckOtherUserWantsAccess(); console.log(new Date().toTimeString() + ": away"); }; var awayBackCa

我试图在单击按钮时清除间隔,但它并没有清除间隔,因为我也尝试过使用全局范围。以下是设置间隔的函数:

/* call idle js */
var awayCallback = function () {
    window.userLog = new Date().getTime();
    CheckOtherUserWantsAccess();
   console.log(new Date().toTimeString() + ": away");
};

var awayBackCallback = function () {
    window.userLog = new Date().getTime();
   console.log(new Date().toTimeString() + ": back");
};

var onVisibleCallback = function () {
    window.userLog = new Date().getTime();
   console.log(new Date().toTimeString() + ": now looking at page");
};

var onHiddenCallback = function () {
    window.userLog = new Date().getTime();
    CheckOtherUserWantsAccess();
    console.log(new Date().toTimeString() + ": on hidden callback");
};


//this is another way of using it
var idle = new Idle({
    onHidden: onHiddenCallback,
    onVisible: onVisibleCallback,
    onAway: awayCallback,
    onAwayBack: awayBackCallback,
    awayTimeout: 120000 //away with 120 seconds of inactivity
}).start();
console.log(idle);
function CheckOtherUserWantsAccess() {

    var url = window.location.href;
    var array = url.split("/");
    var reversed_array = array.reverse();
    if(window.location.href.indexOf("qualification") > -1) {
       var action = reversed_array[2];
    }
    else
    {
        var action = reversed_array[0];
    }

    if (jQuery.inArray(action, pageArray) !== -1) {

        var blueprint_id = '';
        if ($("#lock_blueprint_id").length) {
            blueprint_id = $("#lock_blueprint_id").attr("class");
        }

        if (typeof (window.pageLockMsg !== undefined) && window.pageLockMsg === "Page locked") {
        } else {
            $.ajax({
                type: "post",
                data: {check_action: action, blueprint_id: blueprint_id},
                url: "/pagelock/checkotheruserwantaccess",
                success: function (res) {
                    if (res == 'save your work') {
                        showSaveWorkDialog(action, blueprint_id);
                    } else {
//                        console.log('<--------- continue working ---------->');
                    }
                }
            });
        }
    }
}

/* Set flag to true for want page access by locked user */

setTimeout(function () {
console.log("set timeout");
    if (typeof (window.pageLockMsg !== undefined) && window.pageLockMsg === "Page locked") {

        var url = window.location.href;
        var array = url.split("/");
        var reversed_array = array.reverse();
        if(window.location.href.indexOf("qualification") > -1) {
           var action = reversed_array[2];
        }
        else
        {
            var action = reversed_array[0];
        }

        if (jQuery.inArray(action, pageArray) !== -1) {
            var blueprint_id = '';
            if ($("#lock_blueprint_id").length) {
                blueprint_id = $("#lock_blueprint_id").attr("class");
            }

            $.ajax({
                type: "post",
                data: {check_action: action, blueprint_id: blueprint_id},
                url: "/pagelock/wantaccess",
                success: function (res) {
//                    console.log(res);
                }
            });
        }
    }
}, 5000);

/* show save work popup */
function showSaveWorkDialog(action, blueprint_id) {
alert('page Lost Access');


    $('#saveWorkDialog').modal({
            backdrop: 'static',
            keyboard: false
    }); 

    var n = $('.timespan-20').attr('id');
    var c = n;
    $('.timespan-20').text(c);

    interval = setInterval(function () {
        console.log("still going");
        c--;
        if (c >= 0) {
            $('.timespan-20').text(c);
        }
        if (c == 0) {

            /* remove the access for the user */
            $.ajax({
                type: "post",
                data: {check_action: action, blueprint_id: blueprint_id},
                url: "/pagelock/deleteuseraccess",
                success: function (res) {
                    $(".abc").addClass('masterTooltip_right');
                    $(".abc").find("a").attr('rel', '#pagelockDialog');
                    $("input").attr('disabled', 'disabled');
                    $("textarea").attr('disabled', 'disabled');
                    $(".save-btn").css('display', 'none');

                    $('.masterTooltip_right').hover(function () {
                        // Hover over code

                        var title = $(this).attr('title');
                        $(this).data('tipText', title).removeAttr('title');
                        $('<p class="tooltip4"></p>')
                                .text(title)
                                .appendTo('body')
                                .fadeIn('slow');
                    }, function () {
                        // Hover out code

                        $(this).attr('title', $(this).data('tipText'));
                        $('.tooltip4').remove();
                    }).mousemove(function (e) {
                        var mousex = e.pageX - 30; //Get X coordinates
                        var mousey = e.pageY + 10; //Get Y coordinates
                        $('.tooltip4')
                                .css({top: mousey, left: mousex})
                    });

                    window.pageLockMsg = "Page locked";

                    $("#saveWorkDialog").find(".warning-locking-content").html('<a><img alt="warning" src="/images/warning-logo.png"></a><p style="margin:-41px 0 0 110px;">Your access has been lost.</p>');

                    $(".save").attr("title", "Your access has been lost.")

                    console.log('your access is revoked.');
                }
            });
        }
    }, 1000);
}

/* Update the pageaccess time for the user who has read/write access */
setInterval(function () {
console.log("set interval");
    if (typeof (window.pageLockMsg === undefined) && window.pageLockMsg !== "Page locked") {

        var url = window.location.href;
        var array = url.split("/");
        var reversed_array = array.reverse();
        if(window.location.href.indexOf("qualification") > -1) {
           var action = reversed_array[2];
        }
        else
        {
            var action = reversed_array[0];
        }

        if (jQuery.inArray(action, pageArray) !== -1) {
            var blueprint_id = '';
            if ($("#lock_blueprint_id").length) {
                blueprint_id = $("#lock_blueprint_id").attr("class");
            }

            $.ajax({
                type: "post",
                data: {check_action: action, blueprint_id: blueprint_id},
                url: "/pagelock/updatepageaccesstime",
                success: function (res) {

                }
            });
        }
    }
}, 30000);

我不确定问题从何而来,我们可能需要一个完整的模拟问题的工作样本

不过,如何在JS中处理事件,以便更好地控制范围:

(function($) {
    $(document).ready(function() {
        var interval;
        function showSaveWorkDialog(action, blueprint_id) {
            alert('page Lost Access');
            interval && clearInterval(interval); // avoid the previous interval to continue "unhandled"
            interval = setInterval(function() {
                console.log("still going");
                //...
            }, 1000);
        };

        $('body').on('click','a.clear-interval', function(e) {
            console.log(interval)
            interval && clearInterval(interval);
            interval = 0;
            return false;
        });
    });
}(jQuery));
链接:

<a class="clear-interval" data-dismiss="modal"><i class="fa fa-check" aria-hidden="true"></i> OK</a>
OK

此外,面向对象的方法可以帮助您更好地控制范围:

system = {
  interval :false,
  showSaveWorkDialog: function(action, blueprint_id){
    // ...
    system.interval && clearInterval(system.interval); 
    system.interval = setInterval(function() {
        //...
    }, 1000);
  },
  clickLink: function(){
    system.interval && clearInterval(system.interval); 
    system.interval=false;
  }
}


<a onclick="system.clickLink()" ... >
系统={
间隔:假,
showSaveWorkDialog:函数(操作、蓝图\u id){
// ...
system.interval&&clearInterval(system.interval);
system.interval=setInterval(函数(){
//...
}, 1000);
},
单击链接:函数(){
system.interval&&clearInterval(system.interval);
系统间隔=假;
}
}

当您创建间隔时,一个完整的函数会写入其中,但当您试图清除它时,同样需要做的事情。 尝试使用下一个系统:

var interval = setInterval(logtext,1000);

function logtext(){
  console.log("Its working");
}
然后,要清除它,只需使用

clearInterval(interval);

我喜欢使用的另一个系统:

var interval = null;

    function startinterval(){
      if (!interval) {
        interval = setInterval(logtext,1000);
      }
    };
    function stopinterval(){
      if (interval) {
        clearInterval(interval);
        interval = null;
      }
    };
然后使用:

startinteval();
stopinterval();

在您尝试按下该按钮之前,
window.interval
的值是多少?尝试用console.log替换警报,并用
window.interval
替换
interval
。何时设置间隔?我认为你设定的时间间隔不是为了清除它。请尝试一个断点(调试器),并查看在尝试清除该断点时是否定义了间隔。@Dinca还有另一个函数调用该函数,该函数依次设置interval@Booster2ooo它向我显示了未定义。你确定
onHiddenCallback
checkOtherUserWantAccess
showSaveWorkDialog
正在被调用?如果不检查
interval
的值,调用
clearInterval(interval)
没有什么害处-
clearInterval()
只会忽略
未定义的
或以前被清除的interval ID。但是,是的,OP应该在调用
setInterval()
之前调用
clearInterval()
。在
stopInterval()之后再次调用
startInterval()
不会创建新的间隔,因为您没有重置
interval
变量。我忘记了它,现在很高兴它起到了作用;-)坚持这种方式,它的优雅!
startinteval();
stopinterval();