The problem you have is that you're trying to use .delay()
as a replacement for the native setTimeout()
, which isn't what it's intended to do. The .delay()
function is designed to add a pause between jQuery animation effects, not to delay the execution of another function, and doesn't accept a callback function. See the jQuery documentation for the .delay()
function.
As has already been covered in previous answers, you can use the native setInterval()
function to implement the delay you're after:
function random(){
$("#randomImage1").animate({opacity: '0.0'}).load("../images/randomImage.php").animate({opacity: '1.0'});
setInterval(random, 2000);
}
random();
Note that this will animate the #randomImage1
element back to full opacity, and set the interval to call the function again, even if the AJAX call from .load()
didn't return a success response. If that's not what you want, you can instead move that code into an anonymous function passed as the success callback on .load()
, like so:
function random(){
$("#randomImage1").animate({opacity: '0.0'}).load("../images/randomImage.php",
function() {
$("#randomImage1").animate({opacity: '1.0'});
setInterval(random, 2000)
});
}
random();