jQuery auto play script of pagination - javascript

My Script :
function pagination(id)
{
$("#article_load_destacados").load("indexer_destacados_news.php?pg_d="+id);
if (id+1>2)
{
pagination(0);
setInterval(function()
{
pagination(0);
}, 4000);
}
else
{
setInterval(function()
{
pagination(id+1);
}, 4000);
}
}
</script>
<div id="article_load_destacados"></div>
<script>
pagination(0);
</script>
Create this script for show pagination, the script call PHP file and load this with pagination, for this send different ids and when load PHP file load the same time different elements of pagination. With this script I want run all pagination based on id. If I have for example 5 pages, the script run from 0 to 5, I use for setInterval for it with jQuery.
I want get the script paginate and send different id each 4 seconds.
The problem when run the script the navigator doesn't work, and generates an infinite loop.

As pointed out you want setTimeout not setInterval, you can also simplify your code http://jsfiddle.net/rayBt/
var imax = 3;
var time = 500;
function pagination(id){
$("#article_load_destacados").load("indexer_destacados_news.php?pg_d="+id);
id = (id + 1) % imax;
setTimeout(function () {
pagination(id);
}, time);
}

setInterval is used to have a function repeat at a given interval. Because you're calling setIntveral recursively, your script will be executing pagination with many different values once pagination starts.
You should use setTimeout instead. setTimeout starts a function after a given period of time, which sounds like what you want.

Related

Redirecting script on webpage with delay location.redirect not working javascript

This is in script tag in my base html
const arraypathname = [`array of paths`]
var i = 0;
```
this function loops array of paths and should redirect on every path url from array with delay
```
function redirectFunc(){
setTimeout(function() {
var path_to_redirect = arraypathname[i];
window.location.redirect(path_to_redirect);
```
this doesn work when i used alert() with path it work and every 3 sec i get alert with different path. Why windows.location.replace not working?
```
i++;
if (i < 10) {
redirectFunc();
}
}, 3000)
}
```
i have a base.html file witch is used on every page on my site and i want to do presentation script witch will loop through all paths on web with delay
```
i dont know why its not working like that when i used alert(path_to_redirect) every
3 seconds it alert me with url

How to added an automatic image slide show that does not clash with the update content function

I have some images that I am displaying through JSON. This file refreshes the content every 10 seconds so the new images added show without a page refresh.
I am struggling to add a slideshow code without the two refresh's clashing with each other.
I would really appreciate some help.
This is my current code.
function update_content() {
$.getJSON("showImages.php", function(data) {
$("#slides").html(
data.result.map(({image1}) => `<img class="slides" src="data:image/png;base64,${image1}" />`).join("")
);
setTimeout(update_content, 10000);
var index = 0;
slideshow();
function slideshow() {
var i;
var x = document.getElementsByClassName("slides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
index++;
if (index > x.length) {index = 1}
x[index-1].style.display = "block";
setTimeout(slideshow, 20000);
}
})
}
$(function() {
update_content()
})
The way this is written, there's no way the refreshes wouldn't clash with each other and cause a large mess in updating. What you have here will, every 10 seconds, do a ping back to the server for some json and then spawn what is essentially a thread (not in the technical sense, but in the behavior sense) that every 20 seconds hides all the slides and shows the first slide. By about 60 seconds into this page running, you now have six instances of the slideshow() function queued to run, the newly created one trying to show the first slide, the next most recently created two showing the second, the next two showing the third, etc. And because network lag is unpredictable, they'll all fire at slightly different times in an unpredictable order.
The main problem is setTimeout(slideshow, 20000). It's not needed as this is currently written. Slideshow() is being run every 10 seconds already from the outer function running every 10; it doesn't need to run separately in its own timeout. And if you're running it at that interval already, the slideshow function is useless anyway, and the server only needs to return one image in its json, and the whole slideshow function can be deleted.
Though I question why you need to do a network round-trip every 10 seconds to begin with. Unless this is some real-time snapshot of a camera feed or something, you can easily just give javascript a large array of images for it to cycle through and maybe do the server ping for new images every 10 minutes or so instead. If you go this route, instead move slideshow() out of the update_content() function and just call it once from the jquery onready function to set it running and leave it be. If you need to call slideshow() in the getJson callback, be sure to cancelTimeout on the previous setTimeout(slideshow, ...)'s return value, so you don't make pseudo-threads as described above.

Auto refresh specific div and load image with jquery/ajax

I have an internet radio station and I need a script that will display a picture of the current song in a particular dvi with an id. The image is automatically uploaded via ftp to the server each time the song changes..
HTML:
<div id="auto"></div>
JS:
$ (document).ready(function() {
$('#auto').html('<img src="artwork.png"></img>');
refresh();
});
function refresh() {
setTimeout (function() {
$('#auto').html('<img src="artwork.png"></img>');
refresh();
}, 1000);
}
I tried this, but all I get is that the image is loaded, but in case of a change, I have to manually refresh the whole page again..
I'll point out multiple things here.
I think your code is just fine if you are going for the setTimeout recursive calls instead of one setInterval action to repeat it.
File Caching
your problem is probably the browser's cache since you are using the same image name and directory all the time. browsers compare the file name and directory and to decide to load it from its cache or else it will request it from the server. there are different tricks you can do to reload the image from the server in this particular case.
Use different file names/directories for the songs loaded dynamically
Use a randomized GET query (e.g. image.png?v=current timestamp)
Your method for switching
you are replacing the file with FTP, I wouldn't recommend that. maybe you should have all your albums and thumbnails uploaded to the server and use a different dynamic switching for efficiency and less error proneness and will help you achieve method #1 in the previous section better.
Loading with constant refresh
I would like to highlight that if you are using nodeJs or nginx servers - which are event based - you can achieve the same functionality with much less traffic. you don't need a refresh method since those servers can actually send data on specific events to the browser telling it to load a specific resource at that time. no constant refresh is required for this.
You consider your options, I tried to be as comprehensive as I could
At the top level, browser cache the image based on its absolute URL. You may add extra query to the url to trick browser that is another new image. In this case, new URL of artist.png will be artist.png?timestamp=123
Check this out for the refresh():
function refresh() {
setTimeout (function() {
var timestamp = new Date().getTime();
// reassign the url to be like artwork.png?timestamp=456784512 based on timestmap
$('#auto').html('<img src="artwork.png?timestamp='+ timestamp +'"></img>');
refresh();
}, 1000);
}
You may assign id attribute to the image and change its src url
html
<img id="myArtworkId" src="artwork.png"/>
js in the refresh method
$('#myArtworkId').attr('src', 'artwork.png?timestamp=' + new Date().getTime());
You can use window.setInterval() to call a method every x seconds and clearInterval() to stop calling that method. View this answer for more information on this.
// Array containing src for demo
$srcs = ['https://www.petmd.com/sites/default/files/Acute-Dog-Diarrhea-47066074.jpg',
'https://www.catster.com/wp-content/uploads/2018/05/Sad-cat-black-and-white-looking-out-the-window.jpg',
'https://img.buzzfeed.com/buzzfeed-static/static/2017-05/17/13/asset/buzzfeed-prod-fastlane-03/sub-buzz-25320-1495040572-8.jpg?downsize=700:*&output-format=auto&output-quality=auto'
]
$i = 0;
$(document).ready(function() {
$('#auto').html('<img src="https://images.pexels.com/photos/617278/pexels-photo-617278.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"></img>');
// call method after every 2 seconds
window.setInterval(function() {
refresh();
}, 2000);
// To stop the calling of refresh method uncomment the line below
//clearInterval()
});
function refresh() {
$('#auto').html('<img src="' + $srcs[$i++] + '"></img>');
// Handling of index out of bound exception
if ($srcs.length == $i) {
$i = 0;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="auto"></div>

Stopping a Ajax Loop JQuery

I use a ajax code to monitor a folder to count the number of files in that folder that are being copied with a external batch that I didn't have access. I have the following infinite loop that is working quite fine:
function loadProgWav(files){
$("#wav").load("progress_wav.php?file=<?=$row[2]?>");
}
setInterval(function(){ loadProgWav(files) }, 10000);
The ajax return to me a formatted string with a message of how many files have in that folder. But now I need to be able to stop that loop if the progress_wav.php returns false, and show a submit button to redirect to another page of code, but have no idea on how do so.
I'm running the program in a Windows Server 2003 machine with Xaamp.
To stop it, first create it like this:
var interval = setInterval(function(){ loadProgWav(files) }, 10000);
Later, when you want to stop it, simply do:
clearInterval(interval);
This method also applies to setTimeout, just use clearTimeout the same way.

How to check the status each 10 seconds with JavaScript?

I have a server (mysite.com/status), which returns number of active tasks (just a single integer).
How can I check number of active tasks each 10 seconds with JavaScript and show user something like:
Number of remaining tasks: XXX
And, if number of tasks is 0, then I should load another page.
Make a function set a new timeout calling itself.
function checkTasks(){
// Make AJAX request
setTimeout(checkTasks, 10000);
}
checkTasks(); // Start task checking
with jQuery for AJAX functions... (untested code)
setInterval(function(){
$.get('http://example.com/status',function(d){
// where there is html element with id 'status' to contain message
$('#status').text('Number of remaining tasks: '+d)
if(d == 0){
window.location = '/another/page'
}
})
},10000)
I have thought of different approach, without any AJAX. As you just need to show simple plain data, just use <iframe> to show that dynamic data then with simple JS "reload" the frame every 10 seconds.
HTML would be:
Number of remaining tasks: <iframe id="myFrame" src="mysite.com/status"></iframe>
And the JavaScript:
window.onload = function() {
window.setTimeout(ReloadTime, 10000);
};
function ReloadTime() {
var oFrame = document.getElementById("myFrame");
oFrame.src = oFrame.src;
window.setTimeout(ReloadTime, 10000);
}
Live test case, using time for the same of example.
With some CSS you can make the frame look like part of the text, just set fixed width and height and remove the borders.
setInterval(function(elem){ // here elem is the element node where you want to display the message
var status=checkStatus(); // supposing that the function which returns status is called checkStatus
if(status == 0){
window.location = '/another/page'
}
else {
elem.innerHTML="Number of remaining tasks:"+status;
}
},10000)
Using the javascript library jquery, you can set a repeating infinite loop.
That gets the data from a page and then sets the inner html of an element.
http://jsfiddle.net/cY6wX/14/
This code is untested
edit: demonstration updated
Also I did not use the jquery selector for setting the value in case you do not want to use jquery.

Categories

Resources