clearInterval()不清除间隔

时间:2017-05-26 08:05:13

标签: javascript jquery

我正在尝试清除按钮点击的间隔,但它没有清除间隔,因为我已经尝试了全局范围。这是我设置间隔的函数:

/* 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);

点击按钮,我正在尝试clearinterval

<a onclick="clearInterval(interval)" data-dismiss="modal"><i class="fa fa-check" aria-hidden="true"></i> OK</a>

3 个答案:

答案 0 :(得分:0)

我不确定问题出在哪里,我们可能需要一个完整的工作样本来模仿这个问题。

但是,如何在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>

答案 1 :(得分:0)

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

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()" ... >

答案 2 :(得分:0)

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

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();