清除间隔如果(条件)

clearInterval if (condition)

本文关键字:条件 如果 清除      更新时间:2023-09-26

我会如果(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);
    });
});

一个可能的解决方案是:

$(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);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="Save">Save</button>