Problem with the count up timer in javascript

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

I know there have been quite a few threads on this timer, and I’m not on safe ground either with the complexity of what’s going on, or JS itself.

Hey thanks for the suggegstions, I appreciate that. and I tried it but the still has not benn solved
I am posting my complete script.js file so that tere will not be any confusion
This is my script.js file

   //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);
   // timer = setTimeout(gotoNextSlide, "<?php echo $duration * 1000 * 60 / 
   $num_questions; ?>"); // the issue is here in this line 
   }

   //go to previous question
   function gotoPrevSlide() 
  { 
    goToSlide(getCurrentSlide().index() - 1);
  }

  //jquery for changing the questions using keyboard left and right key press
  $(document).keydown(function(e) {
  switch(e.which) 
   {
     case 39: // left
     gotoNextSlide();
   break;
     case 37: // left
      gotoPrevSlide();
 break;

      default: return; // exit this handler for other keys
}
 e.preventDefault(); //to prevent the  action like scroll 
 });

 //show current question
  function getCurrentSlide() 
  {
    return $("#slides .slide:visible");
  }

   //show  next item or element of the current  question
   function gotoNextItem() 
 {      
   goToItem(getCurrentItem().index() + 1);
 }

 //show the previus item of the current  question
  function gotoPrevItem() 
{
  goToSlide(getCurrentItem().index() - 1);
}

  //geting current item of the current question
  function getCurrentItem() 
 {
   return $("#out .dot:visible");
 }

 //creating dots or bullets  equal to no.of questiions
  function goToSlide(index) 
{
   var $slides = $("#slides .slide");
    if (index >= 0 && index < $slides.length) 
 {
   $slides
    .removeClass("active")
    .eq(index)
    .addClass("active");
  $(".dot")
   .removeClass("active")
   .eq(index)
   .addClass("active");
   }
 }

    // creating dots or buullet equal to  items in an expression
    function goToItem(element) 
 {
   var $ele = $(".dotin");
     if (element >= 0 && element < $ele.length)
   {
  $ele
    .removeClass("active")
    .eq(element)
    .addClass("active");
  $(".dots-cont")
    .removeClass("active")
    .eq(element)
    .addClass("active");
   }
  }

 //marking all checkboxes on clciking checkbox named All
  function toggleCheckboxes(name) 
{
 var checked = $(this).prop("checked");
 $('[name="' + name + '"]').prop("checked", checked);
}

 //showing next item afer 3 second
 function showNextItem() 
{
  $nextItem && clearTimeout($nextItem);
  // $nextItem = setTimeout(showNextItem, timer / "<?php echo 
$num_operands; ?>");  // the issue is here in this line 

  $nextItem = setTimeout(showNextItem, 3000);
   var $nextItem = getCurrentSlide().find('.slide-item:not(.visible)').eq(0);  
   if ($nextItem.length) 
   {
      $nextItem.addClass('visible');
       return;
   }  
 // show the answer
  getCurrentSlide().find('.answer').toggleClass('visible');
 } 
         
 //function for reset the form 
  function resetForm()
 {
  return confirm("Are you sure you want to reset your choices?");
 }

function init() 
  {
   $(".show-answer").click(showNextItem);
   //timer for next element
   // $nextItem = setTimeout(showNextItem, timer / "<?php echo 
   $num_operands; ?>");
    $nextItem = setTimeout(showNextItem, 3000);
   $(".goto-next-slide").click(gotoNextSlide);
     //timer for next question slide
     timer = setTimeout(gotoNextSlide, 1000 * 60);
   // timer = setTimeout(gotoNextSlide,  "<?php echo $duration * 1000 * 60 / 
    $num_questions; ?>");
     $(".goto-prev-slide").click(gotoPrevSlide);

  goToSlide(0);
 }

     $(document).ready(init);

                   //script for generate and play button
                    $(document).ready(function(){
                      $("input[name=submit]").click(function(){
                        $("#play").show();
                          $("#img").show();
                           $("#re").show();
                           $("#gen").hide();
                             });
                          });
          
         //disable all inputs when click on generate
           $("input[name=submit]").click(function(){
                        $("input[type=number],input[type=checkbox],select[name=num_operands],select[name=num_digits]").prop("disabled", true);  
                       });

           //enable all input when click on play 
            $("input[name=play]").click(function(){
                        $("input[type=number],input[type=checkbox],select[name=num_operands],select[name=num_digits]").prop("disabled", false);  
                       });
           
           //enable inputs after clicking on reset button
            $("input[name=reset]").click(function(){
                     $("input[type=number],input[type=checkbox],select[name=num_operands],select[name=num_digits]").prop("disabled", false);                     
                      });

             //for reset button 
                     $(document).ready(function(){
                      $("#re").click(function(){
                       $("#gen").show();     
                           $("#play").hide();
                             $("#re").hide();
                      });
                   });

           //checked all checkboxes on clicking  checkbox named All
             $( '.col-75 .toggle-button' ).click( function () {
                 $( '.col-75 input[type="checkbox"]' ).prop('checked', this.checked)
                   });
              
           // script for showing answer on clicking show answer button
                 $(".answer-content").hide();
                    $(".show-answer").click(function(){
                      $('.totl').hide();   
                        $(".answer-content").show();
                          $(".answer-placeholder").hide();
                          });

             //hide answer after going on next question and clicking next button
                 $(".goto-next-slide").click(function(){
                   $(".answer-content").hide();
                 });

          //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);
           
           //adding count up timer after user select 0 as input value to duration field
            var minutesLabel = document.getElementById("minutes");
            var secondsLabel = document.getElementById("seconds");
            var totalSeconds = 0;
            setInterval(setTime, 1000);

           function setTime() {
                    ++totalSeconds;
                     secondsLabel.innerHTML = pad(totalSeconds % 60);
                     minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
            }

           function pad(val) {
                  var valString = val + "";
                   if (valString.length < 2) {
                      return "0" + valString;
                    } else {
                  return valString;
                    }
            }

I am unable to figur out where I am going wrong ,cna you please guide me ?

hey

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

the above code is working already the issue is not in the timer countdown.
I have posed my complete script.js filecan you please check that once if possible ?

I know, I posted that as an example of where I can see that you get your variable (in this case $duration) from your PHP code, breaking out into PHP to echo the value as part of the JavaScript code when the server draws it. But, I don’t think you can use that approach if your script is included by the main html, as it won’t be processed by PHP. In any case, I don’t think you need to do that.

On the two lines in your full code in post 25 that you highlight as being the problem lines, you are using PHP variables $duration, $num_questions in the first, and $num_operands in the second line, which don’t appear to have been defined or assigned a value anywhere in your JS code as far as I can see, and you do say this is the full code.

This section of code:

function showNextItem() 
{
  $nextItem && clearTimeout($nextItem);
  // $nextItem = setTimeout(showNextItem, timer / "<?php echo 
$num_operands; ?>");  // the issue is here in this line 

  $nextItem = setTimeout(showNextItem, 3000);
   var $nextItem = getCurrentSlide().find('.slide-item:not(.visible)').eq(0);  
   if ($nextItem.length) 
   {
      $nextItem.addClass('visible');
       return;
   }  
 // show the answer
  getCurrentSlide().find('.answer').toggleClass('visible');
 } 

references a variable called $nextItem on the very first line, in a way that I don’t understand and mentioned earlier. Then you use that same variable to call setTimeout() on the line you’ve commented out (which I think uses PHP variables, not JS ones), then again on the next line to call setTimeout() with a fixed value, and then define it as a variable on the next line. I can’t figure out what you’re trying to do there. I also don’t know why you’re not calling clearTimeout on the timer variable, as that seems to be the global JS timer-id that you use to start off with.

In my head, you should have some kind of “start” button. This button calls some JS which grabs the values from the form into JS variables, and shows the first slide.

As I said above, it’s a bit more JS than I really know about.

1 Like

@droopsnoot
the below line code is the working code but for specified time which is setting timeout = 3seconds for switching items present inside the current question that is displaying on a slideshow

                $nextItem = setTimeout(showNextItem, 3000);

the below commented code is the code which I want to execute for my pupose
which will set a calculated timeout by using the formula I have mentioned below but it was not working thats why I posted it commented.

          // $nextItem = setTimeout(showNextItem, timer / "<?php echo $num_operands; ?>;"); // the issue is here in this line 

where timer =

 // timer = setTimeout(gotoNextSlide, "<?php echo $duration * 1000 * 60 / 
      $num_questions; ?>"); // the issue is here in this line 
   }

actually I am also developing this type of code first time , and this turned out to be very challenging for me and surely its helping me to improve my technical skills but I am stuck now here

I get that, and I think the problem is that because this is inside your script.js which I think you said is referenced from the main page with a <script src= tag, the file isn’t processed by PHP, so echoing the values won’t help here.

1 Like

How can I provide you my source code if possible ? because I am stuck here badly and its very important to me I tried as much as I can but don’t know why its not getting solved but I will try untill it get solved.

Here is my full source code can you please check it at once ?

https://github.com/kvj2806/finalize

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.