Saturday, 29 November 2014

setInterval()

The JavaScript setInterval function can be used to automate a task using a regular time based trigger. Just to be clear, setInterval() is a native JavaScript function.

Basic setInterval() Example
1
2
3
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.
1
2
3
4
5
6
7
8
$(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.

setTimeout()

The JavaScript setTimeout function can be used in a jQuery script to automate a task using a single-use, time-based trigger.

Basic setTimeout() Example
1
2
3
setTimeout(function() {
      // Do something after 5 seconds
}, 5000);
Tip: you can use the ClearTimeout() function to clear any timer values previously stored.
1
2
timeout = setTimeout('timeout_trigger()', 3000);
clearTimeout(timeout);

More setTimeout() Examples

1
2
3
4
jQuery(document).ready(function () {
    //hide a div after 3 seconds
    setTimeout( "jQuery('#div').hide();",3000 );
});
Or in a different way:
1
2
3
4
jQuery(document).ready(function () {
    //hide a div after 3 seconds
    setTimeout(function(){ jQuery("#div").hide(); }, 3000);
});