如何在setInterval

时间:2017-09-12 04:59:04

标签: javascript jquery

嗨,朋友,我这样做有麻烦..

     getSocketPerSecond = function () {
            Interval_PerSecond = setInterval(function () {
              $.ajax({
                url: "/asset/ashx/GetSocket.ashx",
                type: "post",
                success: function (data) {
                switch (Status) {
                    case "opendoor":                        
                     openDoor();
                        break
                    case "closedoor":
                     closeDoor();
                        break                 
                }
            }, error: function () { }
        })
    }, 500)
}

function openDoor(){
console.log('Open Door');}

function closeDoor(){
console.log('Close Door');}

控制台日志来了

ajax request // opendoor string
Open Door
ajax request
Open Door
ajax request
Open Door
ajax request // closedoor string
Close Door
ajax request
Close Door
ajax request
Close Door

我希望控制台就像这样

 ajax request
Open Door
 ajax request
 ajax request
 ajax request
 ajax request
Close Door
 ajax request
 ajax request
 ajax request
 ajax request

我试图制作但是真的不知道自从ajax重复以来一直运行一次,所以我需要帮助。 千谢谢。

1 个答案:

答案 0 :(得分:0)

您需要跟踪已处理的最后状态,以便了解它何时发生变化:

getSocketPerSecond = function () {
    var lastStatus;

    Interval_PerSecond = setInterval(function () {
        $.ajax({
            url: "/asset/ashx/GetSocket.ashx",
            type: "post",
            success: function (data) {
                if (lastStatus === Status) {
                    return;
                }

                lastStatus = Status;

                switch (Status) {
                    case "opendoor":                        
                        openDoor();
                    break
                    case "closedoor":
                        closeDoor();
                    break                 
                }
            },
            error: function () { }
        })
    }, 500)
}

function openDoor() {
    console.log('Open Door');
}

function closeDoor() {
    console.log('Close Door');
}