jQuery code snippet to do something every 5 seconds. The jQuery setInterval function can be used to automate a task using a regular time based trigger.
This function is very similar to the jQuery setTimeout() Function.
Basic setInterval() Example
setInterval(function() {
// Do something every 5 seconds
}, 5000);
Tips: If your changing images dynamically load variables from a PHP script you will need to add some sort of random number to the script so that it forces a refresh in all browsers. You can do this by using the following code to generate a random number.
$(document).ready(function()
{
var refreshId = setInterval( function()
{
var r = (-0.5)+(Math.random()*(1000.99));
$('#img-container').load('images/gallery/best/random.php?'+r);
}, 5000);
});
Tips: You might also have to use the ajax method instead of load, to prevent the AJAX request to be cached.
Tips: Alternatively, you could stick header(“Cache-Control: no-cache, must-revalidate”); towards the top of your random.php file to prevent the browser from caching.






Just an FYI to save cionfusion for people later on…
RE:
setInterval isn’t a jQuery function it is a native function of Javascript!
just a clean example… but as already said setinterval is javascript native function
Yeah, seriously, setTimeout() and setInterval() have nothing to do with jQuery… They are pure vanilla JavaScript, available long before jQuery was even a thought.
Also, fix the formatting on your second example. Line 3 should be indented another level.
@Greg – thanks for the constructive comments. Code indentation fixed up.
@Chris, Nepal – noted.