0

How to wait and delay for 5 seconds for the next lines? When i used setTimeout,but it wont wait

here's my code

<script>
  $("#btnSubmit").click(function () {
    var lines = $('textarea').val().split('\n');
    for (var i = 0; i < lines.length; i++) {
      chk(lines[i]);
      //wait after get request completed and need to delay for 5 seconds for next lines
    }
  });
  function chk(i) {
    $.get("check.php?domain=" + i)
      .done(function (data) {
        $("#mt > tbody").append(data);
        $("#curResult").text(i);
        return;
      })
      .fail(function () {
        console.log("error");
        return;
      })

  }
</script>
  • your code is bad. If you put any async request into void function, you can't wait. If you send request, you need wait for response, it jquery and others does by promises. – daremachine Jan 25 '21 at 01:40

1 Answers1

0

You need something that. (This is raw code, not tested)

<script>
  var cnt = 0;
  var loop = 0;
  $("#btnSubmit").click(function () {
    var lines = $('textarea').val().split('\n');
    cnt = lines.length;

    chk(lines[0]);
  });
  function chk(i) {
    $.get("check.php?domain=" + i)
      .done(function (data) {
        $("#mt > tbody").append(data);
        $("#curResult").text(i);

        loop++;

        if(loop === cnt) return;

        setTimout(() => chk(lines[loop]), 5000);

      })
      .fail(function () {
        console.log("error");
        return;
      })

  }
</script>
daremachine
  • 2,678
  • 2
  • 23
  • 34