clearInterval if(condition)

时间:2016-03-12 14:03:21

标签: javascript jquery html

我想如果(NArray === 2){clearInterval()}但我不知道怎么做,因为如果我把它放在setInterval中它显然不起作用并且是如果我把它放在外面也一样。谢谢大家

$(function Intervallo(){
    var NArray = -1;
    var ringraziamenti = [
        "",
        "Thanks",
        "You saved my Website",
        "Now you can use it, and try to find all the hidden tresure that there are",
        "Good Luck",
    ];
    $("#Save").click(function() {
        if (NArray === -1) {
            clearInterval();
        }
        setTimeout(function() {
            $("head").append('<link href="https://fonts.googleapis.com/css?family=Italianno" rel="stylesheet" type="text/css"/><style>body {font-family:"Italianno", cursive; font-weight:800; font-size:36px;}</style>');
        }, 3000);
        setInterval(function () {
            NArray = NArray + 1;
            $("#magia").remove();
            $("#BGimage").css("background-image", "url(../../Desktop/Senza%20titolo-1.png)");
            $("#ringraziamenti").html(ringraziamenti[NArray]);
        }, 3000);
    });
});

1 个答案:

答案 0 :(得分:0)

可能的解决方案是:

&#13;
&#13;
$(function Intervallo() {
  // declare variable to save the return value of setInterval
  var interval = null;
  var NArray = -1;
  var ringraziamenti = [
    "",
    "Thanks",
    "You saved my Website",
    "Now you can use it, and try to find all the hidden tresure that there are",
    "Good Luck",
  ];
    $("#Save").click(function () {
    if (NArray === -1) {
    if (interval != null) {
    clearInterval(interval);
    interval = null;
    }
    }
    setTimeout(function () {
    $("head").append('<link href="https://fonts.googleapis.com/css?family=Italianno" rel="stylesheet" type="text/css"/><style>body {font-family:"Italianno", cursive; font-weight:800; font-size:36px;}</style>');
    }, 3000);
    // save the return value of setInterval
    interval = setInterval(function () {
    NArray = NArray + 1;
    if (NArray == 2) { // when NArray is 2 stop setInterval
       NArray = -1;
       clearInterval(interval);
       interval = null;
    }
    $("#magia").remove();
    $("#BGimage").css("background-image", "url(../../Desktop/Senza%20titolo-1.png)");
    $("#ringraziamenti").html(ringraziamenti[NArray]);
}, 3000);
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<button id="Save">Save</button>
&#13;
&#13;
&#13;