JQuery fadeIn fadeOut with setInterval working sporadically


When using jQuery’s fadeIn() and fadeOut() methods with setInterval(), the animations can sometimes appear to work sporadically, especially if the timing is not set up properly. Here are some tips to help you ensure that your animations work smoothly:

  1. Use setTimeout() instead of setInterval(): It’s generally better to use setTimeout() instead of setInterval() to avoid stacking up multiple calls if the animation takes longer than expected to complete. Instead, use setTimeout() to schedule each individual animation.

  2. Use the complete callback: You can use the complete callback of the fadeOut() and fadeIn() methods to chain the animations together. This ensures that each animation completes before the next one starts.

  3. Use stop() to clear any unfinished animations: If you’re chaining animations, it’s important to call stop() on the element to clear any unfinished animations before starting a new one.

Here’s an example of how you can use setTimeout() and the complete callback to fade in and out an element every 3 seconds:

<!DOCTYPE html>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
		#myDiv {
			width: 100px;
			height: 100px;
			background-color: #ccc;
			display: none;
	<div id="myDiv"></div>
			function fadeOutIn() {
				$("#myDiv").fadeOut(1000, function(){

			}, 3000);

In this example, we first create a div element with an id of myDiv and hide it using the display property.

We then define a function called fadeOutIn() that fades out the #myDiv element for 1 second, and fades it back in for 1 second using the complete callback.

Finally, we use setInterval() to call the fadeOutIn() function every 3 seconds.

Note that you can customize the timing and animation settings to suit your specific needs.