用于循环问题的jQuery的setInterval

时间:2016-05-24 13:58:43

标签: javascript jquery loops timer setinterval

我试图每x秒运行一个特定的for循环,但似乎无法使`setInterval工作。我确信我的语法不正确,但我似乎无法做到正确。

我在下面添加了完整的代码:

jQuery的:

//Click saves this.id as userID
$(function() {
  var rTitle, rText, qTitle, qText, numRows, userID;
  $("#buttons").find(".btn").click(function() {
    $(this).parent().toggleClass('fullscreen');
    $(this).parent().siblings().toggleClass('master');
    var userID = this.id;

    //userID is then used for ajax to PHP script, information passed back is put in variables and generateProblems function is run
    $.ajax({
      type: "POST",
      url: 'include/responseget.php',
      dataType: 'json',
      data: {
        userID: userID
      },
      success: function(json) {
        rTitle = json.rTitle;
        rText = json.rText;
        qTitle = json.qTitle;
        qText = json.qText;
        next = json.next;
        numRows = json.numRows;
        id = json.id;
        generateProblems();
      }
    });

  });
  //Generate draggable html with an interval of 1000
  function generateProblems() {
    $('<div>' + qTitle + '</div>').data('number', qTitle).attr('id', 'question').attr('class', 'bold').appendTo($("#" + id).parent()).hide().fadeIn(2000);
    for (var i = 0; i < numRows; i++) {
      setInterval(function() {
        $('<div>' + rTitle[i] + '</div>').data('number', next[i]).attr('id', +next[i]).appendTo($("#" + id).parent()).draggable({
          containment: '.site-wrapper',
          stack: '#testpile div',
          cursor: 'move',
          revert: true
        }).hide().fadeIn(2000)
        $('<div>' + rText[i] + '</div>').data('number', next[i]).attr('id', +next[i]).appendTo($("#" + id).parent()).hide().fadeIn(2000);
      }, 1000);
    }

   //Rest of the code is not important, but I put it in nonetheless.
    $('#testdrop').droppable({
      drop: handleDropEvent,
      accept: '#testpile div'
    });

    function handleDropEvent(event, ui) {
      var problemNumber = ui.draggable.data('number');
      ui.draggable.draggable('disable');
      ui.draggable.draggable('option', 'revert', false);
      $("#testpile").children().hide();

      $.ajax({
        type: "POST",
        url: 'include/responseget.php',
        dataType: 'json',
        data: {
          userID: problemNumber
        },
        success: function(json) {
          rTitle = json.rTitle;
          rText = json.rText;
          qTitle = json.qTitle;
          qText = json.qText;
          next = json.next;
          numRows = json.numRows;
          generateProblems();
        }
      });

    }
  }
});

PHP:

<?php  include 'login.php';
    if(isset($_POST['userID'])){
        $id = $_POST['userID'];
        $stmt = $conn->prepare("SELECT DISTINCT AnswerTitle, AnswerText, QuestionTitle, QuestionText, Next FROM question_answers
        INNER JOIN question
        ON question_answers.QuestionID=question.QuestionID
        INNER JOIN answer
        ON question_answers.AnswerID=answer.AnswerID
        WHERE AnswerGroup = ?;");
        $stmt->bind_param('s', $id);
        $stmt->execute();
        $result = $stmt->get_result();

          while($row = $result->fetch_assoc()) 
          {
              $rTitle_array[] = $row['AnswerTitle'];
              $rText_array[] = $row['AnswerText'];
              $qTitle = $row['QuestionTitle'];
              $qText = $row['QuestionText'];
              $next_array[] = $row['Next'];
              $numRows = ($result->num_rows);
          }

        $response = array(
            'rTitle' => $rTitle_array,
            'rText'  => $rText_array,
            'qTitle' => $qTitle,
            'qText'  => $qText,
            'next'  => $next_array,
            'numRows'  => $numRows,
            'id'  => $id
        );

        echo json_encode($response);
    }

    // close connection
    mysqli_close($conn);
?>

1 个答案:

答案 0 :(得分:1)

听起来就像你试图获得每秒添加一行的效果一样。你可以使用递归。

此外,setInterval适用于多次通话。 setTimeout只需一次通话。

function generateProblems(i)
{
    // if we're at the end then stop
    if(i == numRows) return;

    // wait 1000
    setTimeout(function()
    {
        // do what you want with i here

        // call the next iteration
        generateProblems(i + 1);
    }, 1000);
}

// then you kick it off with the 0 index
generateProblems(0);

或者如果您希望第一次迭代立即启动:

function generateProblems()
{
    // if we're at the end then stop
    if(i == numRows) return;

    // do what you want with i here

    // move to next row
    ++i;
    setTimeout(generateProblems, 1000);
}

// global var to keep track of where we are
i = 0;
generateProblems