At times, the animation in SetInterval may experience interruptions

I have created an animation using a sequence of images. The animation runs smoothly with the setinterval function, but for some reason, it occasionally pauses. I've shared a fiddle where you can see this pause happening.

Click Here to See the Unwanted Pause

myAnim = setInterval(function(){
  $("#myImageHolder8").attr('src', nextImage5[u]);
  u++;
  if(u==nextImage5.length)
  {
    u=0;
  }
}, 50);

Friends, please help me with this issue.

Answer №1

To avoid potential delays, it is advisable to preload images instead of setting the image source inside a loop. This precaution will prevent disruptions that may occur due to the time taken for loading and decoding images, especially when the process exceeds 50 ms (whether cached or not). Random appearance of issues, particularly on slower devices or connections, can be resolved by preloading images and inserting them into the designated container afterwards.

There are two common methods for preloading images - concealing them in DOM and triggering loading using window.onload, or employing JavaScript with an array and load counter. Below is an example of a loader:

View Live Demo

var images = [],
    count = nextImage5.length,
    len = count,
    i = 0;

for(; i < len; i++) {
    var img = new Image;
    images.push(img);
    img.onload = loader;
    img.src = nextImage5[i];
}

function loader() {
    count--;
    if (count === 0) {
        ... initiate animation at this point...
    }
}

In the animation loop, you can use a similar approach like below (adapted jQuery code):

$('#myImageHolder8').html('');
$('#myImageHolder8').append(images[u]);

Answer №2

Prior to initiating the animation, ensure that you have preloaded your images. This will ensure that the images are prepared and loaded for smooth display. Consider utilizing a tool such as this image preloader. Instead of directly changing the src attribute of an <img> element, it is recommended to render the image onto a <canvas> element and then switch between <canvas> elements for your subsequent images.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are Fabric.js tools for "Drop Zones"?

Has anyone successfully created a "drop zone" similar to interact.js using fabric.js? I haven't had the chance to experiment with it myself. I have some ideas on how I could potentially implement it, but before diving in, I wanted to see if anyone el ...

Tips for preserving scroll position within a division following the redisplay of a division in Vue.js

Within my Laravel and Vue project, I have set up a feature to display posts in a scrollable area. This area is only visible when the 'showFeed' variable is true. <div v-show="showFeed" class="scroll-container" v-scroll=&quo ...

Is there a way to prevent Mac users from using the back and refresh buttons on their browser?

There seems to be a common trend of disabling the back button or refresh button on Windows using JS or Jquery to prevent F5 from working. Can this same method be applied to CMD+R on Mac computers? ...

Losing authentication token when refreshing with Nuxt asyncData and Axios

While testing a get API that retrieves an array of mail data through Postman, everything seems to be working smoothly. However, when I implement the asyncData method to fetch the array in my code, it only works once. Upon page refresh, I encounter a 401 er ...

Setting up vue-apollo 3.0.0 Beta

Seeking guidance as a newcomer in this field. I have experience with Authentication using Apollo client, but I'm stuck when trying to integrate the new vue-apollo-plugin into my Vue-cli-3 generated project. Specifically, I'm confused about how an ...

Observables and the categorization of response data

Understanding Observables can be a bit tricky for me at times, leading to some confusion. Let's say we are subscribing to getData in order to retrieve JSON data asynchronously: this.getData(id) .subscribe(res => { console.log(data.ite ...

Using factories in controllers does not function properly in Angular 1.6

My head is spinning with this one. There are 3 files in play: app.js, app.services.provider.js, admin.js In app.js, I set up my module: (function() { angular.module('myApp', ['ngRoute']).config(function ($routeProvider) { ...

Selenium mistakenly chooses the incorrect element by selecting the first sibling element instead of searching within the element itself

I've been trying to loop through a list of elements and display the text, but I've encountered a strange issue with Selenium. When I select an element inside another element, Selenium returns the element inside the first sibling element instead o ...

Sending data from a JSP page to a JavaScript function

I am working on a script that dynamically adds text boxes based on a specific time interval. <script type="text/javascript> $(document).ready(function() { var data = $('#data').val(); var counter = 1; var d = new Date(); va ...

Creating multipart/form-data with varying Content-Types for each part using JavaScript (or Angular)

Apologies for the confusion, please refer to my update below I have a requirement to link my AngularJS Project with an existing RESTful API. This API uses POST requests that involve uploading a file and submitting form data in a request. However, one of t ...

Subject: Enhancing Page Filters with jQuery Multiple Checkboxes

Here I am continuing the discussion from a previous question on jQuery Multiple Checkbox Page Filter. This is my own unique question. My objectives are threefold: I aim to create a list of checkboxes for filtering page content. I want only the content t ...

Employ jQuery to send data to a php script

I am currently developing a search engine and I am trying to send data from jQuery to PHP. Below is the jQuery code I am using: <script> $(document).keypress(function(e) { if(e.which == 13 && $('#textfield').val()) { $ ...

Determine in Typescript if a value is a string or not

In my code, I have a component: export type InputData = string | number | null; interface InputData { data?: string | number | null; validate: boolean; } const App: React.FC<InputData> = ({ data = '', validate = true, }) => ...

What is causing onbeforeunload to consistently display a dialog box?

I'm facing an issue where my javascript code displays a confirmation dialog even when there is no unsaved data. I have simplified the problem to this bare minimum: window.addEventListener("beforeunload", (e) => { e.returnValue = null; retu ...

After updating to Chrome version 65, I noticed an unexpected error popping up: The onClick listener was expected to be a function, but instead, it

I recently encountered an error in my React app that has been causing some issues. https://reactjs.org/docs/error-decoder.html?invariant=94&args[]=onClick&args[]=string Minified React error #94: Expected onClick listener to be a function, instea ...

HTMLElement addition assignment failing due to whitespace issues

My current challenge involves adding letters to a HTMLElement one by one, but I'm noticing that whitespace disappears in the process. Here's an example: let s = "f o o b a r"; let e = document.createElement('span'); for (let i ...

Angular.js: The $setDirty() method on a form does not automatically affect its child form elements

Currently, I am working on a form validation project using Angular.js. A specific challenge that I am facing is setting the dirty state on a child element of a form in an isolated scope within a directive. Does anyone know how to achieve this and set the i ...

Is there a way to simultaneously modify several data variables within a Chart.js label?

I'm currently working on dynamically updating a line chart with two data entry points using the variable name "data." Take a look at the code snippet below: var lion = new Chart(ctx2, { type: "line", data: { labels: ["Apr", "May", ...

Having trouble loading the JSON file

Having trouble loading a json file, encountering an error saying "TypeError: e is undefined". Not sure if $.each(data.Dishes) is correct or should it be $.each(data.Dishes.Lunch). This is the current script: $(document).ready(function() { $(".lunch_s ...

Developing an interactive menu for mobile devices utilizing a combination of JSON, HTML, JavaScript, and CSS

Creating a custom dynamic menu for mobile platforms using HTML, JavaScript, and CSS with a JSON object downloaded from the server. Not relying on libraries like jQuery. I've come across advice stating that "document.write" should not be used in event ...