javascript - jQuery for 循环问题的 setInterval

标签 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);
?>

最佳答案

听起来就像您正在尝试获得每秒添加一行的效果。您可以使用递归。

此外,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

关于javascript - jQuery for 循环问题的 setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37415835/

相关文章:

javascript - 尝试更改图表 Canvas 的高度和宽度

javascript - React - 变量未定义而不是 true/false - 组件首先呈现?

java - 为什么 ArrayList 给出无序输出?

loops - 如何使用ansible循环

python - 如何在循环中填充pandas数据框?

c# - 导航后无法调用在注入(inject) Web 浏览器文档的代码中创建的 JavaScript 对象的方法

javascript - 悬停时显示框是 "transparent"?

jquery simplemodal动态高度

javascript - 使用 jquery 设置高度

javascript - 如何将属性添加到 img 标记以在 ajax 调用中使用