Tips for executing a task continuously for a minimum duration of 3 seconds

As I work on creating a WordPress template, I am trying to incorporate an image display during the page loading process. However, I want this loading period to last a minimum of 3 seconds. Is there a way to specify a function execution time? Currently, I am using `$ ( window ) .load ()` to add a class to a div within the page for display. The current setup works fine, but I specifically need the loading image to be visible for at least 3 seconds before removing the added class after the window load event. Below is my code:

<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div class="loader">
    loading image   
</div>

<div class="content">
    main content
</div>


<script  src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">         </script><!-- jQuery -->



</body>
</html>

This is my CSS:

.loader{
    position: fixed;
    top: 0;
    bottom:0;
    right: 0;
    left: 0;
    background-color: blue;
    z-index: 999;
    display: none;
}

.show-loader{
    display: block;
}

.content{
    background-color: red;
    height: 600px;
}

This is the JQuery section:

jQuery(document).ready(function($) {


    $(window).load(function() {
        $('.loader').addClass('show-loader');
    });
    $('.loader').removeClass('show-loader');
});

Answer №1

If you need to trigger an event after a specific amount of time, you can utilize a timer function like setTimeout(). It's not entirely clear what your goal is, but if you simply want to remove a class three seconds after adding it, you can use the following code:

jQuery(window).load(function() {
    jQuery('.loader').addClass('show-loader');
    // Remove the class after three seconds
    setTimeout(function() {
        jQuery('.loader').removeClass('show-loader');
    }, 3000);
});

I have removed the jQuery(document).ready() part from the code as it doesn't seem necessary. The jQuery(window).load() event always occurs after the .ready() event and the window object is always accessible.

Answer №2

If you want to delay the execution of your Javascript code for 3 seconds or 3000 milliseconds, you can simply wrap it in a function.

jQuery(document).ready(function($) {


  $(window).load(function() {
    $('.loader').addClass('show-loader');
  });

  setTimeout(loadImage, 3000);
}

function loadImage(){ 

  $('.loader').removeClass('show-loader');
  }); 

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

Shimmering effect on hover for CSS animation

Is there a way to create a CSS-only animation that fades in and out until hovered when displayed in full? I can achieve both effects separately, but I'm struggling to make them work together. The hover element doesn't seem to be functioning prope ...

Load the index file using any URL parameter in the Express.js Router's "catchall" feature

I have a simple setup for my project, including server.js file in the root directory with the following code: app.use('/', express.static(__dirname + '/public/')); In addition, there is a public folder containing index.html, styles, a ...

Can basic logic be applied to CSS?

Recently, I have been experimenting with CSS to blur NSFW images in a chatroom until they are hovered over. I have successfully accomplished this task and now my next goal is to implement checkboxes that can toggle the display of these images. I am aware o ...

Polymer elements fail to adapt to varying screen sizes

I am currently working on creating a responsive website using polymer, but I have encountered an issue where certain elements (such as core-toolbar and paper-fab) are not scaling properly on smaller, denser screens like smartphones. After browsing through ...

What are the steps for performing projection in TypeScript?

Looking to fill up the orders array, which consists of objects of type Order. The desired output is orders=[{id:1,qt:4},{id:2, qt:2},{id:3,qt:2}]. How can I achieve this using TypeScript? I am new to this language. export class Product { constructor(publ ...

Recurly.js version 3 with additional features

I'm currently exploring the functionality of addons in Recurly.js v3. For my form, I've linked a recurly.Pricing instance and added a checkbox for an optional addon: HTML <label for="plan-mobile" class="checkbox"> <input type="check ...

Decoding the significance of this JavaScript import statement

Recently, I stumbled upon some code that looks like this: import React, { Component } from 'react'; I'm curious to know what sets it apart from this syntax: import { React, Component } from 'react'; In my coding experience, I s ...

Obtain information on the Node.js server transmitted from the Ajax jQuery on a client side

Currently, I am utilizing ajax jquery in order to transmit an image to the nodejs server. However, I have hit a roadblock when it comes to receiving the image on the nodejs server from the client. Here is the code snippet from the client: jQuery.noConfli ...

Tips for sorting an array based on various criteria from a separate array

Seeking assistance with filtering results from the data array using two arrays. var data = [{"role":"Frontend", "languages": ["HTML", "CSS", "JavaScript"]},{"role":"Fullstack", ...

Is it acceptable to compare a boolean with a string?

In my code, I have a variable called isRefreshed which is initially declared like this: var isRefreshed = ''; Sometimes, in certain scenarios, isRefreshed can be assigned a boolean value, for example: isRefreshed = false; Now, there is an if ...

The error message appeared as a result of the bluebird and mongoose combination: TypeError: .create(...).then(...).nodeify is

Recently, I encountered an issue while attempting to integrate bluebird with mongoose. Here's the scenario: I wrote some test code using bluebird without incorporating mongoose, and it worked perfectly. The code looked something like this: A().then( ...

Retrieve the next 14 days starting from the current date by utilizing Moment.js

Looking to display the next 14 days in a React Native app starting from today's date. For example, if today is Friday the 26th, the list of days should be: 26 - today 27 - Saturday 28 - Sunday 01 - Monday 02 - Tuesday ............ 12 - Friday Is ther ...

Transform the functionality of DIV and UL to mimic that of a SELECT element

I am attempting to update the text of the <span class="hideSelect"> element to match the text of the selected <li>, so that it functions like a <select> element. CSS: .myDrop { border: 1px solid #ddd; border-radius: 3px; padding: ...

What is the best way to loop through JSON data obtained from a fetch() request and incorporate it into chart data?

I've been working on pulling JSON responses from an API to use in a Chart.js chart within my Vue component. Here's the JavaScript code snippet I'm using: import LineChart from './LineChart.js' export default { name: ' ...

Utilizing jQuery to Calculate the Value of a Duplicate Option ID Selected in Select Elements

I'm having trouble figuring out how to properly title this issue. I am working on a page where I need to calculate the total of multiple select inputs and display the sum whenever a select input changes. All of the select inputs have the same name at ...

Leveraging UseRouter.query Data in Next.js Content Display

I'm currently diving into routing in Next.js and running into an issue where the query values are not being included in the HTML response. Despite recognizing that isReady is false and the return is happening before the variables are set, I'm uns ...

Troubleshooting a Redux issue: Problem with undefined 'props' when using compose

I am new to using react and I keep encountering this error: TypeError: Cannot set property 'props' of undefined Upon removing the following code, the props seem to work fine: export default compose( withStyles(styles,{name:'MainLayo ...

The API for executing Apps Script returns an unauthenticated error

My application is encountering an issue with the Apps Script execution API, while other APIs are functioning properly. The error code 401 is being thrown with the message: "Request is missing required authentication credential. Expected OAuth 2 access toke ...

Unveiling the secret to organizing messy code in node_modules for better readability in React applications

When I need to access files in node modules, I often come across compressed code that is difficult to read. My prettier formatter doesn't seem to format these files. Is there a way to clean up the raw code and make it more readable, similar to regular ...

Exploring the capabilities of Typescript arrays by implementing a forEach loop in conjunction with the

I possess an array: set Array ( [0] => Array ( [name0] => J [name1] => L [name2] => C ) [1] => Array ( [data0] => 3,1,3 [data1] => 5,3 ...