Search code examples
javascriptphpajaxsetintervalcountdown

Trigger a countdown when a set interval function is called


I am retrieving a random user every 60sec via ajax get. In addition I want to trigger a timer which indicates the user when the next 'random user' will be displayed.

I have tried to create two separate functions, one for the ajax get and the other one for the timer. These functions are called in a setinterval function. However, this does not work properly.

<script type="text/javascript">
        window.onload = function random_user() {

            /*ajax request*/
            $.ajax({
                type: "get",
                url: "random_user.php",
                async: "false",
                success: function (data) {
                    $('#random_user').html(data);
                    console.log(data)
                }
            });

            /*Countdown script*/
            function countdown() {
                var counter = 60;
                var interval = setInterval(function () {
                    counter--;
                    if (counter <= 0) {
                        clearInterval(interval);
                        return;
                    }else{
                        $('#time').text(counter);
                        console.log("Timer --> " + counter);
                    }
                }, 1000);
            }

            /*Final function call*/
            setInterval(function () {
                random_user();
                countdown();
            }, 60000); //60000 milliseconds = 60 seconds
        }
    </script>


    <ul class="accordion">
        <li>
            <a>1 user - <span id="time">60</span> sec</a>
            <div class="dropdown">
                <div id="random_user"></div>
            </div>
        </li>
    </ul>

Any help is highly appreciated since I am relatively new to php and javascript. Best regards


Solution

  • You don't need two separate intervals. Your countdown timer can call random_user() if counter==0.

    Finally simply start the countdown after the succesful ajax request.

     window.onload = function random_user() {
    
       /*ajax request*/
       $.ajax({
         type: "get",
         url: "random_user.php",
         async: "false",
         success: function(data) {
           $('#random_user').html(data);
           console.log(data);
           countdown();
         }
       });
    
       /*Countdown script*/
       function countdown() {
         var counter = 60;
         var interval = setInterval(function() {
           counter--;
           if (counter == 0) {
             clearInterval(interval);
             random_user();
           } else {
             $('#time').text(counter);
             console.log("Timer --> " + counter);
           }
         }, 1000);
       }
     }