简体   繁体   中英

Error in setInterval function in JavaScript

I am trying to create a javascript and php quiz. The code is simple: it uses ajax request to check the answer if any of the option button is clicked. It is working fine but after an user clicks any of the given option I want the question to be changed automatically making a new ajax request after 2 seconds. So I used SetInterval function with load function to load the new question. Now the main problen is here: When I click any of the option button the next question appears and goes and again appears. The question keeps jittering as if it is an animation error. So is wrong in the below code thats making this happen?

Code: ( CSS is removed )

index.php

<!DOCTYPE html>

<head>
    <title>Quiz</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style type="text/css">

    </style>
    <script src="jquery.min.js"></script>
    <script>
        function loadqn() {
            $('.optioncont').load('loadit.php?id=1');
        }

        function checkans(qid, optn) {

            $(".optioncont").css("opacity", "0.5");
            var id = qid + 1;
            alert(id);
            setInterval(function () { $('.optioncont').load('loadit.php?id=' + id); }, 2000);

            $.ajax({
                url: 'quiz.php',
                method: 'POST',
                data: {
                    qnid: qid,
                    ans: optn
                },
                success: function (data) {
                    if (data == 'C') {
                        $(".resultN").hide();
                        $(".resultY").show();
                        setInterval(function () { $(".resultY").hide(); }, 3000);
                    } else {
                        $(".resultY").hide();
                        $(".resultN").show();
                        setInterval(function () { $(".resultN").hide(); }, 3000);
                    }
                }
            });
        }


        $(document).ready(function () {
            $("#play").click(function () {
                alert('id');
                loadqn();
            });
        });

    </script>
</head>

<body>

    <div class="qncont">
        <button id="play">Play</button>
        <center>
            <div class="optioncont">
            </div>
            <div class="resultY">
                <div class="congrats">Correct Answer</div>
            </div>
            <div class="resultN">
                <div class="congrats">Wrong Answer</div>
            </div>


    </div>

</body>

</html>

loadit.php

<?php
$conn = mysqli_connect('localhost', 'root', 'bibek');
if (!$conn) {
    die("Database connection Failed" . mysqli_error($conn));
}
$select_db = mysqli_select_db($conn, 'test');
if (!$select_db) {
    die("Database selection falied" . mysqli_error($conn));
}

if (isset($_GET['id'])) {
    $qid = $_GET['id'];

    $query = mysqli_query($conn, "select* from `quiz` where id='$qid'");

    $row      = mysqli_fetch_array($query);
    $question = $row['question'];
    $option1  = $row['option1'];
    $option2  = $row['option2'];
    $option3  = $row['option3'];
    $option4  = $row['option4'];

    echo "<div class='question'>$question</div>";
    echo "<div class='option_block'><a href='#' class='option' onClick='checkans(" . $qid . ",1)'>$option1</a></div>";
    echo "<div class='option_block'><a href='#' class='option' onClick='checkans(" . $qid . ",2)'>$option2</a></div>";
    echo "<div class='option_block'><a href='#' class='option' onClick='checkans(" . $qid . ",3)'>$option3</a></div>";
    echo "<div class='option_block'><a class='option' href='#' onClick='checkans(" . $qid . ",4)'>$option4</a></div>";
} else {
    echo "error";
}
?>

SetInterval will call your function repeatedly with an interval of x milliseconds. You should use setTimeout or better requestAnimationFrame .

Note that you can cancel any setInterval or setTimeout with the clearInterval and clearTimeOut respectively.

As @sjeiti wrote you should use setTimeout instead of setInterval .

The reason for you so called jittering is because the code continues with withe the ajax-call until the 2 seconds has pasted. So you should set your ajax-call inside your first Timeout-function

    function checkans(qid, optn) {

        $(".optioncont").css("opacity", "0.5");
        var id = qid + 1;
        alert(id);

        //THE CODE WON'T WAIT FOR THIS TO COMPLETE 
        setInterval(function () { $('.optioncont').load('loadit.php?id=' + id); }, 2000);

        //IT WILL JUMP TO THIS PART WHILE IT'S WAITING FOR THE TIMEOUT
        $.ajax({
            url: 'quiz.php',
            method: 'POST',
            data: {
                qnid: qid,
                ans: optn
            },
            success: function (data) {
                if (data == 'C') {
                    $(".resultN").hide();
                    $(".resultY").show();
                    setInterval(function () { $(".resultY").hide(); }, 3000);
                } else {
                    $(".resultY").hide();
                    $(".resultN").show();
                    setInterval(function () { $(".resultN").hide(); }, 3000);
                }
            }
        });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM