Why can't you initialize a slide show from elements generated and applied within JS without delaying the processing with setTimeout?

Asked 2 years ago, Updated 2 years ago, 44 views

We are trying to implement the process of initializing a slide show (bxSlider) for that structure after appending a dynamically created element.

"At this time, I tried to initialize the slide show with ""1"", but it didn't initialize well, so
" It works well like 上手く

If you prepare the structure in advance with static HTML and hit the initialization, it will work normally. There does not appear to be a problem with the HTML structure or the bxSlider() plug-in itself.

  • What is the possible reason why が is not allowed and が is OK?
  • Is it possible to achieve the desired behavior without using setTimeout()?

JS:

var htmlArray=(function(){
  // $.ajax retrieves json from server, generates elements and stores them in array
  return myarray;
})();

vari = 0;
var$t=$('#target');

for(i;i<htmlArray.length, i+=1){

  // Append structures in order
  $t.append(htmlArray[i]);

  // I want to initialize the slide show after the last one.
  if(i===htmlArray.length-1){
    htmlArray[i].ready(function(){

      // === これIt doesn't work well with this===
      $t.bxSlider();

      // === これThis works well====
      setTimeout(function(){
        $t.bxSlider();
      }, 100);
    }
  }
}

DOM image just before bxSlider initialization:

<divid="target">
  <div class="item"><a href="article-url">
    <p>Title String</p>
    <p><img src="img/img.jpg"/>/p>
  </a></div>
  <div class="item"><a href="article-url">
    <p>Title String</p>
    <p><img src="img/img.jpg"/>/p>
  </a></div>
  <div class="item"><a href="article-url">
    <p>Title String</p>
    <p><img src="img/img.jpg"/>/p>
  </a></div>
</div>

javascript jquery

2022-09-30 17:26

2 Answers

If it works "well" if it runs asynchronously, it depends on what happens after $t.bxSlider() calls the unknown function of htmlArray.ready().
As I've said many times here, JavaScript is a single thread, so setTimeout always runs after the thread that invokes you (JavaScript doesn't even have to wait for synchronization, so it's always after the thread is finished).
With this program, if you run htmlArray[i].ready() after it's all done, it's probably a discrepancy in the order of processing.


2022-09-30 17:26

There was a reload slider in the samples on the official page, but I think it can be realized now.

http://bxslider.com/examples/reload-slider

Please forgive me if it's wrong.

That's all.


2022-09-30 17:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.