Home > Mobile >  Why is my variable having unexpected value?
Why is my variable having unexpected value?

Time:08-14

I have five (5) images displayed on a page. All but the first image is hidden. Each image is having an id f1,f2,..... f5. So I created an interval to display other images with a next variable that determines which image is to be slid i.e if next is equal to 2, f2 should be displayed while others should be hidden.

It works fine except that on the first run of the set interval, I expect the next slide to be 2 as defined but it shows 1.

It is sliding images at specified interval but slide 1 would be displayed for 10 seconds this because the next variable is having a value of 1 at first interval run.

 import {Helper} from '../../../public/js/helpers.js';

 const help = new Helper();


//next image to slide
let next = 2;

//total num of slides
let total = Number($(".Flash").length);

//function to run slides
function slide() {
  alert(next) //This will come with 1 for the first run.
  //current image slide
  let curr_slide = next - 1;
  //hide current  slide
  $(`#f${curr_slide}`).hide()
  //class name of next slide to know if we have gotten to the end of slide.
  let next_slide_id = $(`#f${next}`).attr("id");
  //no more slide to load,go back to first slide
  if (next > total) {
    next = 1;
    $(`#f${ next}`).show();
    return
  }
  //next slide is available? No!!! But this is not the end of the slides. So skip next slide.
  if ((next_slide_id === undefined) && (next <= total)) {
    next  = 1;
    $(`#f${next}`).show();
    return;
  }

  //display new slide
  $(`#f${next}`).show()
  //increment
  next  = 1;
} //end of function

//arguments needed for method that executes setIntervals
let data = {
  "duration": 5000,
  //duration of each slides
  "run": slide //function to run inside setinterval
}
//slide images now
let sliden = help.set_interval(data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

The helper class where the set_interval method is written is below

    class Helper{
    /*RUN SET INTERVALS*/
      set_interval(args,counter=""){
      let sliden =   setInterval(args.run,args.duration) 
         return sliden;
      }
    }

I'm using php to loop through the images and display it with HTML. The PHP and HTML is

<?php

//Unnecessary part has been left out. just an array that is looped with for each and then echoed as seen below

echo'<div id="f'.$id.'" >

    

    <div >

        <div >

            <figure >

                <img  id="flash-product" src="../../../public/products/'.$array['pic'].'">
            </figure>

            <p style="display:flex; justify-content:center;">
                <span > <i ></i></span>

                <span >  <i ></i></span>
            </p>
        </div>

    </div>

    
</div>';

?>

The php just simply creates 5 images from the loop. And a unique id of f1,f2,...f5 is given to each element. And the first element with id f1 is shown while f2 to f5 is hidden with a CSS class named dn (which sets displays:none;).

So in the js, i am just simply creating a variable called next with an initial value of 2, then it gets element by id of f2 and displays it and hides all other. Next variable increases to 3 then shows f3 and hide all others. Just in that cycle. My questions is that the next variable initial value is defined to be 2 but its coming out with 1 on the first run of set interval which I can't figure out why

I hope you now understand me.

CodePudding user response:

My question is that the next variable initial value is defined to be 2 but its coming out with 1 on the first run of set interval which I can't figure out why

Your total variable is set to the number of elements with the class .Flash:

let total = Number($(".Flash").length);

But something is going on with your PHP loop that you have only 1 element with the class .Flash.

Consequently the condition

if (next > total)

returns true... which means next is reset to 1:

next = 1;

See below:

class Helper{
  /*RUN SET INTERVALS*/
  set_interval(args,counter=""){
  let sliden =   setInterval(args.run,args.duration) 
  return sliden;
  }
}

 const help = new Helper();


//next image to slide
let next = 2;

//total num of slides
let total = Number($(".Flash").length);

//function to run slides
function slide() {
  console.log(next   ' of '   total) //This will come with 1 for the first run.
  //current image slide
  let curr_slide = next - 1;
  //hide current  slide
  $(`#f${curr_slide}`).hide()
  //class name of next slide to know if we have gotten to the end of slide.
  let next_slide_id = $(`#f${next}`).attr("id");
  //no more slide to load,go back to first slide
  if (next > total) {
    next = 1;
    $(`#f${ next}`).show();
    return
  }
  //next slide is available? No!!! But this is not the end of the slides. So skip next slide.
  if ((next_slide_id === undefined) && (next <= total)) {
    next  = 1;
    $(`#f${next}`).show();
    return;
  }

  //display new slide
  $(`#f${next}`).show()
  //increment
  next  = 1;
} //end of function

//arguments needed for method that executes setIntervals
let data = {
  "duration": 5000,
  //duration of each slides
  "run": slide //function to run inside setinterval
}
//slide images now
let sliden = help.set_interval(data)
<div id="f" >

    <div >

        <div >

            <figure >

                <img  id="flash-product" src="../../../public/products/">
            </figure>

            <p style="display:flex; justify-content:center;">
                <span > <i ></i></span>

                <span >  <i ></i></span>
            </p>
        </div>

    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

CodePudding user response:

Thank you a for the help!! I checked the code again and my loop in php is doing the necessary. The 5 images has a class of .Flash. The issue was in another part of the code which I didn't post because I thought it is not too neccessary for the question...

I referenced the next variable in the another part of the code(A setTimeout function) and attached a value of 1 to it. The part is all about removing any image at a specific time(sort of if it expires in the next 1 hour,then remove image). The code is seen below for better understanding...

//loop through each image and remove
for (let i = 1; i <= total; i  ) {

    //day part of the time
    let day = $(`#flash-day${i}`).html();

    //hour part of time
    let hour = $(`#flash-hour${i}`).html();

    //minutes part of time
    let min = $(`#flash-min${i}`).html();

    //seconds part of time
    let sec = $(`#flash-sec${i}`).html();

    let time = `${day}:${hour}:${min}:${sec}`;

    //convert time into seconds
    let array = time.split(":");

    let d = Number(array[0]);

    let h = Number(array[1]);

    let m = Number(array[2]);

    let s = Number(array[3]);

    //convert all to seconds
    time = d * 86400   h * 3600   m * 60   s;

    let variable;

    //run this when image is expired
    variable = setTimeout(() => {

        //stop sliding
        clearInterval(sliden);
        
  //start sliding from 1
        next = 1; //this was why the next variable was set to 1 at first run of interval

        sliden = help.set_interval(data, next);

        $(`#f${i}`).remove();
    }, time * 1000);
}


 

I didn't expect the next variable to be equals 1 until the setTimeout method runs. So I commented out all inside setTimeout except the removal of element and the issue is solved.

Thanks for your time in assisting me!!!

  • Related