Is it possible to establish a delay for requestAnimationFrame()?

My webpage has a very long layout with text in one column and a floating element in another. I want the floating element to follow the scroll of the window and return to its original offset once scrolling stops.

The current code I have is:

var ticking = false;
var box = document.getElementById('box1');

window.addEventListener('scroll', function() {
  ticking = ticking || requestAnimationFrame(function() {
    ticking = false;
    var top = window.scrollY;
    console.log(top);
    box.style.transform = 'translateY(' + top + 'px)';
    box.style.transition = 'all 100ms ease-out';
  }); 
});

 

#left {
  width: 200px;
  margin: 50px;
  position: relative;
  float: left;
}

#right {
  float: left;
  width: 800px;
  font-size: 200%;
}

#box1 {
  width: 100px;
  height: 100px;
  background: red;
  position: absolute;
  top: 50px;
}

 

<div class="outer">
  <div id="left">
    <div id="box1"></div>
  </div>
  <div id="right">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...[truncated for brevity]

Visit my Codepen page for reference

However, I am experiencing flickering of the element during scrolling. This might be due to frequent modifications of transform: translateY(). Is it possible to introduce a delay similar to setTimeout() or setInterval()? Alternatively, is there a better approach to achieve this effect? If not, can anything be done to reduce the flickering?

Answer №1

When utilizing CSS transitions, there is no need to use requestAnimationFrame as they are automatically managed during the "animation frame." Simply introduce a delay using transitionDelay:

window.addEventListener('scroll', function() {
    var top = window.scrollY;
    console.log(top);
    box.style.transform = 'translateY(' + top + 'px)';
    box.style.transition = 'all 100ms ease-out 1s';
});

The flickering of the box occurs because it jumps by only a few pixels and eases out before reaching the next scroll point.

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

Bootstrap wysiwyg5 editor validation: Ensuring accuracy in your content creation

Currently, I have integrated the Bootstrap wysiwyg5 editor into a form. One of the fields in this form, specifically the text area, is mandatory and cannot be left empty. I am facing a challenge in validating whether the user has entered any content into t ...

The React OnClick and onTouchStart event handlers are functioning properly on a desktop browser's mobile simulator, but they are not responsive when

I added a basic button tag to my next.js main page.js file that triggers an alert when clicked. Surprisingly, the onClick function is functional on desktop browsers but fails to work on any mobile browser. "use client"; export default function P ...

Unable to retrieve the second number enclosed in parentheses using regular expressions

Currently, I am diving into the world of regex and encountering a set of strings formatted as "(9/13)". My goal is to retrieve the second number in this format. To achieve this, I experimented with the following regex pattern: /\(.*?[^\d]*(\ ...

Removing the previous value in React by shifting the cursor position - a step-by-step guide

I have successfully created a phone using React that saves the numbers in an input field whether you press the keys or use the keyboard. Although the phone is functioning well, I am facing an issue where pressing the delete button or backspace key always ...

Concurrent HTTP Requests - AngularJS

My directive, known as machineForm, includes a dataService: dataService.getMachineTaxesById($scope.machineId).then(function (response) { $scope.machine.machineTaxes = response.data; }); I am using this directive twice simultaneously. <div class= ...

retrieve information from a div using an AJAX request

I don't have much experience with ajax and javascript, but I need some assistance, so I will do my best to explain clearly! Below is the JavaScript associated with a button: $('#button-confirm').on('click', function() { $.ajax({ ...

Arrange three images and three text lists in a horizontal layout with responsiveness

Struggling with a HTML/CSS challenge here! I'm attempting to vertically align 3 images and text in the pattern of image, text, image, text, image, text. Everything looks great on my 13" MacBook, but once I start resizing the window, chaos ensues. Any ...

Bring life to the process of adding and removing DOM elements through animation

I am seeking to provide an engaging and interactive experience for my users while ensuring responsiveness. To achieve this goal, I have decided to learn more about web development by creating a card game. My current setup involves clickable elements that ...

Navigating websites: Clicking buttons and analyzing content

When looking to navigate a website's directory by utilizing buttons on the page or calling the associated functions directly, what language or environment is most suitable for this task? After experimenting with Python, Java, Selenium, and JavaScript, ...

Explore within another map and analyze the node to spot the differences

I have some questions about iterating through a JavaScript Object and using array functions in JavaScript. Let's assume I have the following variables: var json1 = "[{"id": 1, "name":"x"}, {"id": 2, "name":"y"}]"; var json2 = "[{"id": 1, "name":"x"}, ...

Is there a way to prevent this React function from continually re-rendering?

I recently created a small project on Codesandbox using React. The project involves a spaceship that should move around the screen based on arrow key inputs. I have implemented a function that detects key presses, specifically arrow keys, and updates the ...

Tips for uploading information and posting it on a different page with mongoDB and Node.js

I am looking to implement a feature on a website where data is submitted to MongoDB from one page, and then retrieved and displayed on another page. The technologies I am working with include node.js, express, Mongoose, and MongoDB. Currently, the data is ...

Is it necessary to make multiple calls following a successful AJAX request?

Here is an AJAX call I am setting up. The first step is to hit the endpoint dofirstthing.do. Once that is successful, the next step is to make another call with "param1" as the query parameter. Now, my question is - how can I make a third call with "param ...

Assign tags using a variable within a loop

Consider the scenario where I need to generate a list of li elements: {map(listItems, (obj,i) => <li key={i}> <a target="_blank" href={obj.itemName === 'view_detail' ? `event/${id}` : ''} > <i c ...

Maximizing Performance: Enhancing Nested For Loops in Angular with Typescript

Is there a way to optimize the iteration and comparisons in my nested loop? I'm looking to improve my logic by utilizing map, reduce, and filter to reduce the number of lines of code and loops. How can I achieve this? fill() { this.rolesPermiAdd = ...

Issue with Three.js GLTF loader peculiar behavior while attempting to incorporate three-dimensional text

I had an idea to import a prebuilt gltf scene created in Blender, then add some 3D text using the ttf loader and manipulate it. Each loader worked perfectly when used separately, but strange things started happening when I combined them into a single scrip ...

Anticipated a task or procedure but encountered an expression instead

I'm encountering an issue with the following code snippet. JShint is flagging it with "Expected an assignment or function and instead saw an expression". function checkVal(inputField) { ( inputField.val() === '' ) ? inputField.prev( ...

Receiving POST data in the req.body object with only the key specified in Express.js

I am encountering an issue with my current POST request. There is a simple function in place that handles the sending of data to the server using AJAX. handleSubmit(event) { var http = new XMLHttpRequest(); // object allows for making http requests // ...

Creating a standalone card using Bootstrap

Trying to create this... https://i.stack.imgur.com/PMRSI.png However, I'm unsure of how to achieve it. <div class="row justify-content-center"> <div class="col-3 me-3" style="background-color: #F1F3F8; border-r ...

Is there a more efficient method for iterating through this object?

Working with JSON and JS var data = { "countries": { "europe" : [{name: "England", abbr: "en"}, {name: "Spain", abbr: "es"}], "americas" : [{name: "United States"}], "asia" : [{name: "China"}] } }; JavaScript Loop for (k in data) { fo ...