What is the best way to arrange this script?

I am currently working on a Javascript script that automatically scrolls down and loads a new URL when it reaches the bottom of the page. However, I would like to add a delay of 30 seconds before the new URL is loaded.

Although I am relatively new to Javascript, I have managed to create a functioning script. However, I believe there may be an issue with the order or syntax of the code.

While the script successfully scrolls to the bottom of the page, it does not wait for 30 seconds as intended, despite the inclusion of a delay function.

Below is the script I am currently using.

If anyone could assist in rearranging the code to achieve the desired functionality, or provide guidance on how to edit the script appropriately, it would be greatly appreciated. Thank you.

window.scrollTo(0, document.body.scrollHeight);

function delayExecution() {
    /**
     * This function waits for 30 seconds before launching the next line of code.
     */
    setTimeout(function() {
        // Code to be executed after the delay
        console.log("Next line of code executed after 30 seconds");
    }, 30000); // 30 seconds delay
}

// Call the function to delay the execution
delayExecution();

// Function to load a new URL when scroll hits the bottom
function loadNewUrlOnScroll() {
  // Check if the scroll has reached the bottom of the page
  if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
    // Replace the URL with the new URL
    window.location.href = "https://example.com/new-url";
  }
}

// Attach the scroll event listener to the window
window.addEventListener("scroll", loadNewUrlOnScroll);

I attempted to use AI to fix this issue, but it only made things worse, haha.

Answer №1

function scrollToBottom() {
  window.scrollTo(0, document.body.scrollHeight);
}

function delayExecution() {
  /**
   * This function waits for 30 seconds before launching the next line of code.
   */
  setTimeout(function () {
    // Replace the URL with the new URL
    window.location.href = "https://example.com/new-url";
  }, 30000); // 30 seconds delay
}

// Function to load a new URL when scroll reaches the bottom
function loadNewUrlOnScroll() {
  // Check if the scroll has reached the bottom of the page
  if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
    // Call the function to delay the execution
    delayExecution();
  }
}

// Attach the scroll event listener to the window
window.addEventListener("scroll", loadNewUrlOnScroll);

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

Limit users to entering either numbers or letters in the input field

How can I enforce a specific sequence for user input, restricting the first two characters to alphabets, the next two to numbers, the following two to characters, and the last four to numbers? I need to maintain the correct format of an Indian vehicle regi ...

Watching the Event Emitters emitted in Child Components?

How should we approach utilizing or observing parent @Output() event emitters in child components? For instance, in this demo, the child component utilizes the @Output onGreetingChange as shown below: <app-greeting [greeting]="onGreetingChange | a ...

What is the best way to employ the pick function with optional types within nested TypeScript structures?

I am interested in learning TypeScript. dynamicContent?: { data?: { attributes?: { baccarat?: { title?: string | null; content?: string | null } | null; baccaratOnline?: { title?: string | null; content?: string | null } | null; ...

Typescript's Integrated Compatibility of Types

One important concept I need to convey is that if one of these fields exists, then the other must also exist. When these two fields are peers within the same scope, it can be challenging to clearly communicate this connection. Consider the example of defi ...

Is there a way to maintain scroll position on a dynamically refreshing div?

After searching for hours, I still can't find a solution to my problem. I am using a simple JQuery script to refresh a div and display my PHP output in it. $script = " <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery ...

Node Js is a lightweight server that allows for easy querying of URLs

I've been exploring various examples but I'm still struggling to understand how it all functions. My goal is quite simple, or so I thought. I was hoping someone could assist me? The task at hand is to establish a server for clients to connect t ...

Discovering the data from a JSON serialization in JavaScript

Within my PrintViewModel list, there is a sublist called Summary. I am working with ASP.NET MVC. @model CRC.Models.PrintViewModel; <label id="lblTotalMonthlyLoanDeduction"></label> I am serializing it using JSON. var obj = @Json.Se ...

Using JQuery to trigger the onchange event for a select tag

I am working with jQuery where I need to append select tags inside a table for each row. I want to add an onChange event for each dropdown on every row. However, the approach I have taken doesn't seem to be working. This is what my jQuery code looks l ...

Encountering issues with creating a session in Selenium/webdriver while utilizing Safari 12

Ever since making the update to Safari 12, my automated scripts have been encountering a new error: SessionNotCreatedError: Request body does not contain required parameter 'capabilities'. (Interestingly, this error is exclusive to Safari and d ...

Typescript: Determining the return type of a function based on its input parameters

I've been working on a function that takes another function as a parameter. My goal is to return a generic interface based on the return type of the function passed in as a parameter. function doSomething <T>(values: Whatever[], getter: (whatev ...

Different div elements are clashing with each other when it comes to hiding and

Having added multiple div elements with different IDs, I am facing an issue where clicking one div displays it while hiding the others. I am looking for a solution to prevent conflicts between the divs. Any suggestions on what might be causing this problem ...

Tips on successfully transferring row data that has been clicked or selected from one adjacent table to another table

Currently, I am facing a challenge with two tables that are positioned next to each other. My goal is to append a selected row from the first table to the second table. After successfully extracting data from the selected row and converting it into an arr ...

Typescript types for React Native's SectionList: A comprehensive guide

Currently, I am in the process of developing a React Native app using TypeScript. In order to display information in a structured manner, I decided to implement a SectionList. Following the official documentation, I have written the following code snippet: ...

Webpack: The command 'webpack' does not exist as a recognized cmdlet, function, script file, or executable program

Attempting to set up a new project using webpack and typescript, I have created the project along with the webpack file. Following the instructions on the webpack website, I successfully installed webpack using npm install webpack webpack-cli --save-dev ...

How can NodeJS Websocket (ws) facilitate communication between various clients?

In my project, I have a scenario where client1 needs to share information with client2 and the latter should receive an alert upon receiving it. To achieve this, I am utilizing Websocket "ws" with NodeJS. The web page for client1 receives a response via A ...

Generating fresh objects to establish a Many-to-Many connection with Sequelize

I am currently utilizing NodeJS, Express, Sequelize, and PostgreSQL in my project. Within my application, I have defined two models: a "User" model and a "Social" model. My goal is to establish a many-to-many relationship where a user can be associated wi ...

Excluding node modules when not included in tsconfig

Within my Angular project, there is a single tsconfig file that stands alone without extending any other tsconfigs or including any additional properties. Towards the end of the file, we have the following snippet: "angularCompilerOptions": { ...

Storing the selected value from a dropdown box in PHP

Can anyone help me with echoing the $row['price'] based on the user's GPU selection? Your input is greatly appreciated! #adding more content to meet word count requirements. <div id="content"> <table border="1" style="width: ...

Using PHP variables in JavaScript to access getElementById

I have multiple forms displayed on a single PHP page. They all follow a similar structure: <form id="test_form_1" action="test_submit.php" method="post" name="test_form"> <label>This is Question #1:</label> <p> &l ...

Pausing briefly after selecting an element with Webdriver

I have been attempting to highlight an element on a webpage for a specific duration of time, approximately 5-6 seconds. However, I am facing difficulty in making the highlight persist for the desired duration as it currently flashes briefly. Despite using ...