Problem with the count up timer in javascript

hey is here any way that instead of using label I could show it in other way ?

any way you can think of, just a question of complexity.

@ m_hutley

hey I tried by this also but its still not working its still processing the else part even if I gave input of 0 to field

this is new updated logic

                 var startTimer;

              startTimer = function() {
              var time;
               time = 0;
              setInterval((function() {
               var hour, min, sec, str;
               time++;
                 sec = time % 60;
               min = (time - sec) / 60 % 60;
               hour = (time - sec - (min * 60)) / 3600;
               debugger
              count = hour + ':' + ('0' + min).slice(-2) + ':' + ('0' + sec).slice(-2);
               $('.responseTime').text(count);
            }), 1000);
          };

        $( document ).ready(function() {
        startTimer();
      });

This is how I am displaying it

              <div class="col-sm-4">
        <?php if(isset($_POST['duration']) == 0) 
                { ?>
                  <span class="responseTime" style="color:indianred"></span>
                  <?php 
                } 
                 else 
                { ?>
               <div class="timer" style= 'font-size: 25px;color:  #ffe6e6;'>        
                   <?php echo "Duration:" ?>
                     <time id="countdown"><script> var seconds = <?php echo  $duration * 60; ?>;</script>     
                          <?php echo $duration; 
                 } ?>
                    </time>
              </div>
    </div>

the logic for class timer is below which is always running after given input to duration field

                  //script for timer countdown
               function secondPassed() 
                  {
                       var minutes = Math.round((seconds - 30)/60),
                        remainingSeconds = seconds % 60;
                         if (remainingSeconds < 10) 
                          {
                           remainingSeconds = "0" + remainingSeconds;
                          }
                      document.getElementById("countdown").innerHTML = minutes + ":" + remainingSeconds;
                         if (seconds == 0) 
                           {
                              clearInterval(countdownTimer); 
                              window.location.href = 'http://localhost/copied/final_generate/slideshow.php';
                           } 
                       else
                          {
                           seconds--;
                          }
                  }
                     var countdownTimer = setInterval('secondPassed()', 1000);

please tell me what should I do ?

  • These are my form fields using input given to these fields I want to set the timer

        <div class="row">
              <div class="col-25">
                  <label>Duration:</label>
              </div>
              <div class="col-75">
                  <input type="number" id="duration" name="duration" value="0" min="0">
              </div>
       </div>
       <div class="row">
              <div class="col-25">
                  <label for="num_questions">Select No. of questions:</label>
              </div>
              <div class="col-75">
                  <input type="number" id="num_questions" name="num_questions" value="1" min="1" max="100">
              </div>
          </div>
      <div class="row">
              <div class="col-25">
                  <label for="int">How many numbers you want in a sequence? :</label>
              </div>
              <div class="col-75">
                  <select name="num_operands">
                      <option value="2"> 2 </option>
                      <option value="3"> 3 </option>
                      <option value="4"> 4 </option>
                      <option value="5"> 5 </option>
                      <option value="6"> 6 </option>
                      <option value="7"> 7 </option>
                      <option value="8"> 8 </option>
                      <option value="9"> 9 </option>
                      <option value="10"> 10 </option>
                  </select>
              </div>
          </div>
    

    My javascript code for timer

         //script for timer countdown
                 function secondPassed() 
                    {
                         var minutes = Math.round((seconds - 30)/60),
                          remainingSeconds = seconds % 60;
                           if (remainingSeconds < 10) 
                            {
                             remainingSeconds = "0" + remainingSeconds;
                            }
                        document.getElementById("countdown").innerHTML = minutes + ":" + remainingSeconds;
                           if (seconds == 0) 
                             {
                                clearInterval(countdownTimer); 
                                window.location.href = 'http://localhost/copied/final_generate/slideshow.php';
                             } 
                         else
                            {
                             seconds--;
                            }
                    }
                       var countdownTimer = setInterval('secondPassed()', 1000);
    

This iis where I am displaying it

           <div class="timer" style= 'font-size: 25px;color:  #ffe6e6;'>  
             <?php echo "Duration:" ?>
             <time id="countdown"><script> var seconds = <?php echo  $duration * 60; ?>;</script>  <?php echo $duration; ?>
             </time>
          </div>             

This is script I have created for switching no.of questions after 1 minute

          /script for generate one by one questions
         var timer;
        // go to next question
       function gotoNextSlide()
      { 
       timer && clearTimeout(timer);
       goToSlide(getCurrentSlide().index() + 1);
        timer = setTimeout(gotoNextSlide, 1000 * 60);
      }                 
       //show current question
     function getCurrentSlide() 
  {
      return $("#slides .slide:visible");
  }
     //showing next item or number in current question afer 3 second
    function showNextItem() 
   {
     $nextItem && clearTimeout($nextItem);
     $nextItem = setTimeout(showNextItem, 3000);
     var $nextItem = getCurrentSlide().find('.slide-item:not(.visible)').eq(0);  
      if ($nextItem.length) 
    {
      $nextItem.addClass('visible');
       return;
    }  
 } 
   
  function init() 
   {
    //timer for next item or number
    $nextItem = setTimeout(showNextItem,  3000);
    $(".goto-next-slide").click(gotoNextSlide);
   //timer for next question slide
   timer = setTimeout(gotoNextSlide, 1000 * 60);

goToSlide(0);
}

   $(document).ready(init);

My Aim -

  • the first field is of duration , user can give any input to this field for ex he gave input of 4 then 4 minute timer should set.
  • then the no.of questions field , suppose user gave input of 2 the 4 minute timer should set with equal distribution of time to both the questions i.e 120seconds to each question
  • if user gave input of 3 for how many numbers he want in a question then that previous fields 120 seconds should split to adjust these 3 numbers i.e 40 seconds wil be set for each number

NOTE - This is for basically a math quiz in which the questions will be automatically slides(there is a slideshow in the output I am displaying each item in a questions one by one ) using timer along with the numbers inside the questions based on input.

  • Everything is working here but only the timer settings are not working , when I gave input to duration field then the timer is set properly for that input but not for each question , its setting for whole set of questions
  • I have set those 3000(3seconds) just to show for example
    I tried some calculation but they are not helping , How can I aply the calculatins in my script ?

The issue of count up timer is solved now but not the real time calculation issue, please guide me through the issue is merged here in comment 7

1 Like

17 posts were merged into an existing topic: How to show a real time calculation in javascript?

A post was merged into an existing topic: How to show a real time calculation in javascript?

A post was merged into an existing topic: How to show a real time calculation in javascript?

hey @Mittineague thanks for the suggestions , I think I got the way to fix , this issue.

  • the issue of countup timer is solved now and working perfectly fine.
  • BUT there is anothe small issue which is merged here in above comment about the time settting I am bit confused to adjust the time calculations , if possible , can you check that one ?

Sorry, you have too many things going on at the same time with this script that I’m having difficulty following.

Please post the section of code your asking about now.

1 Like

hey sorry to bother you again
actually the issue which I am asking now is merged here above in comment 6 , can you check that one please ?

1 Like

hey I have updated the code which is setting the time to each question by calculating with he help of input fields I have posted above cooment 6

updated script

             //script for generate one by one questions
        var timer;
       // go to next question
        function gotoNextSlide()
      { 
         timer && clearTimeout(timer);
          goToSlide(getCurrentSlide().index() + 1);
          timer = setTimeout(gotoNextSlide, $duration * 60000 / $num_questions);
     }  
  
    //showing next item afer calculated seconds from below
    function showNextItem() 
  {
    $nextItem && clearTimeout($nextItem);
   $nextItem = setTimeout(showNextItem, timer / $num_operands);
   var $nextItem = getCurrentSlide().find('.slide-item:not(.visible)').eq(0);  
   if ($nextItem.length) 
    {
      $nextItem.addClass('visible');
       return;
    }  
   }

     function init() 
   {
     //timer for next element
     $nextItem = setTimeout(showNextItem, timer / $num_operands);
    $(".goto-next-slide").click(gotoNextSlide);
        //timer for next question slide
   timer = setTimeout(gotoNextSlide, $duration * 60000 / $num_questions);
    $(".goto-prev-slide").click(gotoPrevSlide);

  goToSlide(0);
 }

$(document).ready(init);

I have created a formulae to calculate the time but its not working , where I am going wrong ?

What does this line do?

$nextItem && clearTimeout($nextItem);

I’m familiar with using && to represent AND for comparing conditions, but not on its own like this.

I am not that familiar with JS and mainly come in here to learn - I hadn’t realised that variable names starting with a $ were done in JS as well as PHP. It seems confusing to me, given that there is also some PHP code floating around.

I can’t see where your $duration and $num_questions JS variables are coming from, don’t you need to grab the values from the form somewhere?

I Assigned a variable to my setTimeout , which then pass to clearTimeout to clear it,

I sort of see. It’s just not syntax that I am familiar with. More to learn, by the look of it.

  • my script.js file is included in a my home.php tag and in the tag of this home.php my form is exists.
  • my rest of the script is working fine but not the script for timer I have posted above
  • thats the main issue I am having. The time is not calculating by taking input value from form fields in a proper way it only setting timer for the time I specified there .

Where is the code for getting the input value from the form fields? I see you’ve got a formula using $duration and $num_questions, but I don’t see where you assign values to those variables.

1 Like
  • I have posted only those codes which are going to use in the issue so that there will be no confusion after seeing rest of the code
  • here is my code of getting input from form fields
  • this code is present in the same file where my form is exists.
     function get_input_data() {
     $seed = $_POST['seed'] ?? rand();
    $play = $_POST['play'];
    $num_digits = intval($_POST['num_digits']) ?? 1;
    $num_questions = intval($_POST['num_questions']) ?? 1;
    $num_operands = intval($_POST['num_operands']) ?? 1;
    $duration = $_POST['duration'] ?? 0;

    // Read operations from the POST params and map the array that looks like 
    //    ['Addition', 'Multiplication'] as  ['+', '*']
     
    $operations_map = array(
        'Addition'       => '+',
        'Subtraction'    => '-',
        'Multiplication' => '*',
        'Division'       => '/',
    ); 

    $operations = array_map(function($operation_name) use ($operations_map){
        return $operations_map[$operation_name];
    }, $_POST['operation'] ?? []);  

    // generate expressions using the specified random seed
    srand($seed);
    $expressions = array();
    for ($i = 1; $i <= $num_questions; $i++) {
        $expression = generate_expression($num_operands, $operations, $num_digits);
        $expression_string = implode(" ", $expression);
        $result = eval("return ($expression_string);");
        $expressions[] = compact("expression", "result");
    }

    return compact(
        'play',
        'seed',
        'num_digits',
        'num_questions',
        'num_operands',
        'operations',
        'expressions',
        'duration'
      );
    }

That’s your PHP code. In post #15, you have some code that looks like JavaScript (based on setTimeout and var and a couple of other things):

timer = setTimeout(gotoNextSlide, $duration * 60000 / $num_questions);

here which uses variables with a similar name, but you don’t seem to define those variables anywhere that I can see. If you want to use the values from your PHP variables inside your JS code, then surely you’d need to use echo to output them in the JS code when the server draws the page, as you did here:

<time id="countdown"><script> var seconds = <?php echo  $duration * 60; ?>;</script>     

If you’re intending the JS code to run from a browser action rather than when initiated by the server re-drawing the page, you’ll need to get the values from the form in your JS code.

I may be out of my depth here, I’m sure someone will be along to comment if I’m made presumptions that aren’t correct. If those are JS variables, I think that while it might be correct to use variable names in JS that start with a $, it just adds confusion to the code.

1 Like

You’d quite often find that where jQuery has been used, but I’ve not followed the thread closely enough to know whether that’s the case here.

2 Likes