Search code examples
javascriptphpajaxcountdown

How to make countdown instaed of count up


I have this code that displays the timer for the exam. Which made by the admin side. the timer is counting the time in count up but i want to make it display in countdown. Unfortunately i could not figure out how to make it display in countdown. if someone can help me i will be appreciated.

ajax.php

if(isset($_POST['subId']) && isset($_POST['userId'])){
        $subId = $_POST['subId'];
        $id = $_POST['userId'];
        require_once('../admin/inc/db.php');
        $subQuery = "SELECT * FROM subject WHERE id = '$subId' AND exam = 'on' ";
        $subRun = mysqli_query($con, $subQuery);
        if(mysqli_num_rows($subRun) > 0){
            $subRow = mysqli_fetch_array($subRun);
            $time = $subRow['time'];
            $query = "SELECT * FROM timer WHERE user = '$id' AND subject = '$subId' ";
            $run = mysqli_query($con, $query);
            if(mysqli_num_rows($run) == 0){
                $insert = "INSERT INTO timer(user, subject, spent) VALUES('$id', '$subId', 1)";
                $insertRun = mysqli_query($con, $insert);
            } else{
                $row =  mysqli_fetch_array($run);
                $spent = $row['spent'];
                if($spent < $time){
                    $count = $spent + 1;
                    $update = "UPDATE timer SET spent = '$count' WHERE user = '$id' AND subject = '$subId' ";
                    $updateRun = mysqli_query($con, $update);
                    echo $count;
                } else{
                    echo "Time out!";
                }
            }
        } else{
            echo "Time out!";
        }

timer.js

$(document).ready(function(){
    var subId = $('#subId').val();
    var userId = $('#userId').val();
    var myVar = setInterval(myTimer, 1000);
    function myTimer(){
        $.ajax({
            type: 'POST',
            url: 'inc/ajax.php',
            data: { subId: subId, userId: userId },
            success: function(res) {
                if(res == 'Time out!'){
                    clearInterval(myVar);
                    $('#timer').html('Time over!');
                    $('#exampleModal').modal({
                        backdrop: 'static',
                        keyboard: false
                    });
                } else{
                    var time = res;
                    if(time < 60){
                        $('#timer').html('0:' + time);
                    } else if(time == 60){
                        $('#timer').html('1:00');
                    } else{
                        var min = Math.floor(time/60);
                        var sec = time % 60; 
                        if(min < 10 && sec < 10){
                            $('#timer').html(min + ':' + '0' + sec);
                        } else if(min >= 10 && sec < 10){
                            $('#timer').html(min + ':' + '0' + sec);
                        } else{
                            $('#timer').html(min + ':' + sec);
                        }
                    }
                }
            },
            error: function(jqXHR, textStatus, errorThrown){
                if(jqXHR){
                    $('#timer').html('<span class="animated flash infinite">Exam Paused!</span>');
                }
            }
        });
    }
});

Solution

  • To make the timer countdown instead of counting up, you need to change the way the time variable is calculated in the success function of the AJAX request. Instead of subtracting the current time from the start time, you need to subtract the start time from the maximum time and display the remaining time.

    Here's an updated version of the code that should count down:

    $(document).ready(function(){
        var subId = $('#subId').val();
        var userId = $('#userId').val();
        var totalTime = 60; // or whatever maximum time you want to set
        var remainingTime = totalTime;
        var myVar = setInterval(myTimer, 1000);
        
        function myTimer(){
            $.ajax({
                type: 'POST',
                url: 'inc/ajax.php',
                data: { subId: subId, userId: userId },
                success: function(res) {
                    if(res == 'Time out!'){
                        clearInterval(myVar);
                        $('#timer').html('Time over!');
                        $('#exampleModal').modal({
                            backdrop: 'static',
                            keyboard: false
                        });
                    } else{
                        remainingTime = totalTime - res; // calculate remaining time
                        if(remainingTime < 0){
                            remainingTime = 0; // prevent negative values
                        }
                        var min = Math.floor(remainingTime/60);
                        var sec = remainingTime % 60;
                        var timeStr = min + ':' + (sec < 10 ? '0' : '') + sec; // format time string
                        $('#timer').html(timeStr); // display remaining time
                    }
                },
                error: function(jqXHR, textStatus, errorThrown){
                    if(jqXHR){
                        $('#timer').html('<span class="animated flash infinite">Exam Paused!</span>');
                    }
                }
            });
        }
    });
    

    Note that this code assumes that the maximum time is known and fixed, and that the >res variable returned by the AJAX request represents the time elapsed since the >start of the exam. You may need to adjust the code if these assumptions don't hold >for your use case.