Ways to implement a delay in a function?

I'm looking for a way to introduce a delay in my function. Should I enclose the function within a delay function, or is there a different method to ensure that the animation doesn't trigger until 5 seconds after the page has loaded?

var textToType = "blablablabla";
var displayedText = "";

function typeText(fullString, currentlyTyped) {
    if (fullString.length != currentlyTyped.length) {
        currentlyTyped = fullString.substring(0, currentlyTyped.length + 1);
        document.getElementById("logoType").innerText = currentlyTyped;
        setTimeout(function() {
            typeText(fullString, currentlyTyped)
        }, 150);
    }
}

document.getElementById("logoType").innerHtml = textToType;
var element = document.createElement('h2');
element.innerHTML = textToType;
textToType = element.textContent;
typeText(textToType, displayedText);
<a class="navbar-brand" id="topper" href="#"><p id="logoType"></p></a>

Answer №1

I believe the solution you are seeking is using the setTimeout function.

window.setTimeout(function () {
    type(typeThis, displayText);
}, 5000);

You can also incorporate this into a listener to determine when the window has completed loading:

window.addEventListener('load', function () {
    window.setTimeout(function () {
        type(typeThis, displayText);
    }, 5000);
});

Here's a complete example:

var typeThis = "blablablabla";
var displayText = "";

function type(fullString, typedSoFar) {
  if (fullString.length != typedSoFar.length) {
    typedSoFar = fullString.substring(0, typedSoFar.length + 1);
    document.getElementById("logoType").innerText = typedSoFar;
    setTimeout(function() {
      type(fullString, typedSoFar)
    }, 150);
  }
}

document.getElementById("logoType").innerHtml = typeThis;
var element = document.createElement('h2');
element.innerHTML = typeThis;
typeThis = element.textContent;

window.addEventListener('load', function() {
  window.setTimeout(function() {
    type(typeThis, displayText);
  }, 5000);
});
Waiting 5 seconds...
<a class="navbar-brand" id="topper" href="#"><p id="logoType"></p></a>

Answer №3

To incorporate a delay in your JavaScript code, utilize the setTimeout() function in this manner:

let delayID;

function delayedAction() {
  delayID = window.setTimeout(slowAction, 3000);
}

function slowAction() {
  console.log("Executing action after delay!");
}

function clearDelay() {
  window.clearTimeout(delayID);
}

Reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout

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

I have tried using justify-content: center; and align-items: center; to center this div, but the container div is still not centered. How can I successfully center

I am having trouble centering the container in my HTML code HTML code:- <body> <div class="container"> <div class="image"> <img src="./images/image-qr-code.png" alt="qrcode"> & ...

Switching out CSS files on the fly in ASP.NET

Looking to dynamically change the CSS file being used in my ASP.NET Web Application when it's running. Imagine I have two CSS files, red.css and blue.css. I attempted the following method: In the Master Page, I have this link: <link rel="Styles ...

Which specific jQuery functionality was made visible?

When it comes to jQuery, how is it exposed? // Expose jQuery to the global object window.jQuery = window.$ = jQuery; However, there are in fact two versions of jQuery: var jQuery = (function() { // Define a local copy of jQuery var jQuery = function( s ...

Blog entries alternating between a pair of distinct hues

I want to create a design where each post container has a different color from the one next to it. Essentially, I would like the containers to alternate between two distinct colors. The left side shows how it currently appears, while the right side depict ...

Retain the formatting of HTML while extracting the text

Is there a simple way to extract text from HTML source without losing formatting (such as line breaks and spaces)? Currently, my text extraction process looks like this: page_title_element = driver.find_element_by_xpath("x-path") page_title = pa ...

Designing CSS elements that flow from top to bottom, left to right, and extend to the right when overflowing

I'm attempting to create a layout where divs are displayed from top to bottom, but once they reach the bottom of the browser window, any additional divs will overflow to the right. You can take a look at the desired layout here: https://i.stack.imgur. ...

Shifting text higher to the <h1> tag using CSS

I'm currently attempting to move the paragraph header closer to my h1 title. I'm struggling with incorporating the position function and have tried using padding without success. On the image, I am aiming to position the text "Where every connec ...

Manipulating a React table: Customizing a row in the table

Below is the code snippet: const [data, setData] = useState([ {id: 1, name: 'paper', qty: 10}, {id: 2, name: 'bottle', qty: 10}, ]); const [isEditable, setEditable] = useState([]); useEffect(()=>{ data.map(each=>{ ...

Ways to avoid a bootstrap column from wrapping onto a new line when the parent width is decreased

https://i.sstatic.net/gKdAN.png I attempted to decrease the form width by applying padding on both sides of the form using 'px-5'. However, when I implemented this change, the column holding the '#lastName' input shifted to a new line. ...

Is it possible to implement CSS code from a server request into a React application?

With a single React app that hosts numerous customer websites which can be customized in various ways, I want to enable users to apply their own CSS code to their respective sites. Since users typically don't switch directly between websites, applying ...

Adding text after a div in React-JS using Bootstrap: A quick guide

Just starting out with website development and I have a question. As I practice making this website, I am struggling to figure out how to add the text "To know more about us click here" below the 'Get started' button. I tried adding a simple < ...

Creating a JavaScript function for a custom timed traffic light sequence

Currently, I am facing a challenge with my high school project of creating a timed traffic light sequence using JavaScript for my upcoming exams. Unfortunately, I feel quite lost and unsure about how to proceed. My initial plan involves formatting the valu ...

Crafting a template for mixing up images and quotes without any specific connection - here's how!

I came across some interesting templates that can generate random quotes and others that create random pictures. My goal is to develop a template that generates both a random quote and a random picture, similar to this example, without any relation betwee ...

Implementing an alert box upon redirect with PHP

This question is pretty straightforward. I have a form on my index.html page and PHP code to submit that form to an external URL, then redirect back to the index: <?php Echo "<style>body{background:#3e4744}</style>"; Echo "<style>h2{ ...

Is it possible to upload numerous profiles into the MYSQL database using this WP template?

Apologies in advance if my question is unclear, but in simple terms, I am looking to automate the process of uploading hundreds of profiles and jobs to this WP template: The developer of this template has stated that it is not possible to do this through ...

The jQuery call to a web service is returning XML data, but the success function is receiving a

I have utilized: [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)] The outcome of my web service call is: <string xmlns="http://tempuri.org/"> [{_pkId:"",_code:"",_message:"The file has been uploaded successfully.",_sta ...

Automatically generate nested object properties in VueJS for streamlining code structure

Understanding the Issue I have created a custom system to monitor specific "store" properties from a JSON in a NoSQL database. The structure is fairly straightforward, with nested objects that are necessary for various reasons. The data format resembles ...

Changing the size of various types of images

Is there a way in JavaScript to automatically resize and fill in a block with fixed width using different images with various dimensions? I came across something similar, but it was in AS2. I'm unsure if it can be translated to JavaScript. var _loc3 ...

Passing data between pages in Node.js

My current project involves creating a web service using node.js. In this setup, I am utilizing curl to send POST data to my index.js application. The index.js app processes the received data and I need it to then route the output to various pages based on ...

"Get a glimpse of the brackets image with real-time live

I seem to be encountering a strange issue. I have double-checked the source code for my image, and when I view the page in Chrome without using Brackets, the image displays properly. However, when I use Brackets Live preview, the image does not show up i ...