I have an array of ID's that I am returning via Laravel's eloquent.
eg
[0, 1, 4, 6, 8, 9]
These represent ID's in a table and then I am calling a route using those ID's.
/get_single_item/{id}
What I want is to every X seconds, move through the array and call the single_item page each time.
Currently this:
$.each(data, function(value) {
console.log( value );
});
Dumps out all the values in one go of course, how can I only get one value, every X seconds and then start back at the beginning once at the end?
(Revised answer)
It is fairly simple actually:
setInterval()
to increment and clamp the variable and use the corresponding array element var array = [0, 1, 4, 6, 8, 9], current = -1; setInterval(function() { current += 1; current %= array.length; console.log("callback for item #" + current + " whose value is " + array[current]); }, 2000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <!-- nothing here, look at browser console -->
If you want it to print forever this is one way of doing it with a recursive function :)
function print_every_x_second(list, milliseconds) {
// Get the first value and remove it from array
var value = list.shift();
console.log(value);
// Put it back at the end.
list.push(value);
setTimeout('print_every_x_second(list, milliseconds)', milliseconds);
}
var list = [0, 1, 4, 6, 8, 9];
var milliseconds = 300;
print_every_x_second(list, milliseconds);
I made a small library to run a set of functions in a specific queue,
You can use it here for your specific case as the following:
var arr = [1,2,3,4], i = 0;
var fn = function() {
// your business logic is separated from the iteration logic
if(i === arr.length) return;
console.log( arr[i++]);
};
// execute the queue every 1 second
queue([fn], 1000, /* repeat */ true)();
var queue = function(fn,timeout,repeat){
return function(){
var i = 0, f = fn[i], t = setInterval(function(){
f();
if(fn[i+1] !== undefined){
f = fn[++i];
}else{
if(repeat){
i=0;
f = fn[i];
}else{
clearInterval(t);
}
}
}, timeout);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.