Javascript pause issue in loop, ajax, jquery

I am trying to create a simple animation. In short, I have a list of 20 small divs and one outer div. I want to display five small divs within a large div at that time. Ideally, I get a set of the following 5 sections every 5 seconds.
I am using the jquery ajax function to create small divs, here is the code:

$(document).ready(function(){ var amount=0; $.ajax({ type: "GET", url: "SampleServiceIncidentList.xml", dataType: "xml", success: function(xml){ //creates divs within GadgetMain div, works fine. }); amount = $("#gadgetMain").children().size(); //counts how many small divs there are $("#testText").append("amount of children:"+amount); //and displays it in a test field divideFeed(); }//close success }); //close $.ajax( function divideFeed(){ //divides the set of small divs into groups var limit = 5; var pagesNo = Math.ceil((amount/limit)); var minimum=0; var maximum; var i=0; while (i<pagesNo) { minimum= i*limit; maximum=minimum+limit; // // PROBLEM HERE // populate(minimum, maximum); i++; } } function populate(minimum, maximum){ $("#gadgetMain div").addClass('hidden'); //hides all small divs $("#testText").append('<br/>min: '+minimum+' max: '+maximum); //prints current group of divs (0-5; 5-10 etc) $("#gadgetMain div").slice(minimum,maximum).removeClass('hidden'); } 

});

So, the problem is that I can not make it wait 5 seconds to display a group of divs that interest me. I know that it divides divs correctly - when I warn about the minimum and maximum value, it changes the contents of the external div every time I close the warning. But I can not find a way to pause the function.

I would be very grateful for the help, it drove me crazy.

+4
source share
1 answer

You do not want to pause the function; instead, you want to transfer control to the browser and return it after the interval. This function is window.setTimeout . (There is also a related window.setInterval , but I usually prefer setTimeout .)

This requires a bit of logic inversion, but it is very similar to calling Ajax - you ask for something, then release it and ask the browser to call you back when you receive it.

So for example:

 function doSomething(x) { runner(); function runner() { console.log("x = " + x); --x; if (x > 0) { window.setTimeout(runner, 1000); } } } doSomething(10); 

... counts from 10, once per second. doSomething returns almost immediately, but then the runner receives a callback once per second until it stops rescheduling.

+2
source

Source: https://habr.com/ru/post/1300166/


All Articles