Delayed synchronization between CSS animation timing and JavaScript carousel interval causes a slight lag

I am currently working on a slider where one dot grows and another one follows suit. However, I have encountered a strange issue. I set the interval option to 2000ms for the slider and the CSS timing to 2000ms.

div.bubble {
    height: 100px;
    border-radius: 1em;
    width: 100px;
    animation: vars 2000ms infinite ease-in-out; //here the timing is the same as the interval
}

Upon loading the page, the animation and slider initially appear synced, but as the animation continues, a slight lag starts to show in the slideshow. It seems like either the animation is too fast or the slideshow is too fast.

https://jsfiddle.net/pas14r8g/9/

I have provided a fiddle link for better clarity of the situation. Despite trying Swiper, Flickity, and Splide sliders, all seem to exhibit the same issue.

The bug is quite subtle, not noticeable within the first 4 loops, but it gradually appears and worsens.

What I have observed is that the slider consistently lags by 3ms or 4ms. Adjusting the value of the interval option did not resolve this perfectly.

Answer №1

Simply put: The setInterval function sends a periodic request to the window object, instructing it to execute the designated callback function every x milliseconds.

It's important to note that the execution is not guaranteed to occur precisely at x milliseconds; rather, it will happen sometime after x milliseconds have elapsed.

There's always a possibility of the execution taking longer than x, with potential delays of up to 600 milliseconds.

To address this issue, utilizing requestAnimationFrame might be more suitable, as it runs approximately 60 times per second. By keeping track of frame deltas or using an accumulator, you can trigger your desired action after a specific time interval (x milliseconds).

If you observe the code snippet below for a while, you'll notice occasional lag in the output.

function hi() {
  console.log("Hi");
}

function hello() {
  console.log("Hello");
}

let t = Date.now();

function update() {
  if ((Date.now() - t) > 1000) {
    hello();
    t = Date.now();
  }
  requestAnimationFrame(update);
}
update();
setInterval(hi, 1000);

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

Optimal asset management strategies for Angular applications

What is the process for loading assets in an Angular app? Will the app wait for all assets to load before bootstrapping, or will they be lazy loaded if not needed on the initial page? I have a large number of PDFs stored in the assets folder that I load a ...

What causes the shift in the position of the div element?

I have been struggling with a problem in my code. Whenever I hover over this element, it rotates as intended but it also changes its position. I can't figure out why this is happening. Can someone please help me debug this? I would greatly appreciate ...

Having trouble with Vee-validate Basic example - undefined errors issue

I've been struggling to get a basic form validation page working with vee-validate. Something seems to be going wrong, but I can't pinpoint the exact issue. Why am I seeing the error: errors not defined. <!DOCTYPE html> <html> < ...

How to create a Bootstrap panel that collapses on mobile devices and expands on desktop screens?

Is there a simple way to remove the "in" class from the div with id "panel-login" when the screen size is less than 1199px (Bootstrap's xs, sm, and md modes)? I believe JavaScript or JQuery could be used for this, but I'm not very proficient in e ...

Angular Promises - Going from the triumph to the disappointment callback?

It seems like I might be pushing the boundaries of what Promises were intended for, but nonetheless, here is what I am attempting to do: $http.get('/api/endpoint/PlanA.json').then( function success( response ) { if ( response.data.is ...

Why is my PHP function not able to properly receive the array that was sent to it via Ajax?

After retrieving an array through an ajax query, I am looking to pass it to a PHP function for manipulation and utilization of the elements at each index. The PHP function in question is as follows: class ControladorCompraEfectivoYTarjeta { public fu ...

Display issue with alert box

I run a website where users can submit posts and receive alert messages (success or warning) when they do so. The alert messages are displayed at the top of the page using position: absolute to prevent them from affecting the layout when they appear. Every ...

Ways to remove unwanted line breaks following PHP code within HTML documents

Currently working on building my blog, and I'm facing some challenges with the post div. It seems like every element within is automatically getting line breaks. Despite trying to float them or adjust padding, it's not giving me the desired layou ...

Receiving server data with socket.io in Node.js

I have set up a Node.js server to send data to an HTML client using socket.io: var spawn = require('child_process').spawn; var child = spawn('node', ['file.js']); child.stdin.write("Hello there!"); child.stdout.on(&apo ...

What is the best way to refresh the content in a table on all HTML pages?

I'm a new developer with a website that includes over 100 pages, each containing HTML tables. Is there a way to update all table content at once without manually editing every single page? All pages have links inserted in the table that need to be u ...

"Troubleshooting a problem with the height of a collapsible div

I am encountering a peculiar problem with the height behavior of a collapsible div. The expanded height of the div persists even after it is closed or collapsed. Please see the image below for reference: https://i.sstatic.net/OetPL.jpg The JavaScript see ...

What is the purpose of utilizing "({ })" syntax in jQuery?

What is the purpose of using ({ }) in this context? Does it involve delegation? Can you explain the significance of utilizing this syntax? What elements are being encapsulated within it? For instance: $.ajaxSetup ({ // <-- HERE error: fError, ...

When attempting to make an AJAX call using the console, an error was encountered stating that the function $.ajax is not available

Currently experimenting with an ajax call from my console to a local server, but encountering an error: VM4460:1 Uncaught TypeError: $.ajax is not a function(…) Here's the code snippet causing the issue: url = 'http://localhost:8080/testform ...

Ensure the footer remains fixed while scrolling

For the past day, I've been tackling a challenge with my online shop project. On the specific item's page, I want to include a fixed [add to cart] button as a footer initially, which then becomes sticky when scrolling to a certain point. You can ...

"Ensuring a mobile-friendly website menu's z-index is

I'm currently working on developing a responsive menu, but I've encountered some issues with setting the correct Z-index values. The problem arises when trying to add a "show menu" button that expands behind the main content (cwrap) after window ...

Is there a way for me to discover the identity of the victor?

There are 4 divs that move at different, random speeds each time. I am trying to determine which one is the fastest or reaches the goal first. Additionally, there is a betting box where you can choose a horse to bet on. I need to compare the winner with my ...

Leveraging Multiple Angular.js Controllers within a Shared DOM

As someone who is fairly new to Angular.js, I am currently working on integrating it into my Node.js application. While I have successfully created a RESTful API using Angular for a single controller, I am now looking to utilize two or more controllers wi ...

Shortcut to prevent false 0 values

When my server responds, it sends back an object structured as follows: { success: integer } Meanwhile, on the client side I'm using: return body && body.success; The issue arises when the integer is zero, causing the above code to return ...

Canceling ongoing Angular HTTP request does not stop

Is there a way to properly cancel an $https request in Angular when a new request is triggered? Despite using allMarkersRequest.abort(), the pending request still shows up in Chrome's dev tool. What am I missing? In the code snippet below, allMarkers ...

The listener for @ok is not being activated when using jest-test-utils with b-modal in vue-bootstrap

I have implemented the vue-bootstrap b-modal feature with the @ok="save" hook Here is a snippet of mycomponent.vue: <template> <div> <b-button @click="add">open modal</b-button> <b-modal static lazy id="modal-detail" ...