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

The JavaScript program for the shopping list is experiencing issues with the formatting of list items

I have been working on developing a shopping list program using JavaScript. The program includes an input box and an "add item" button, which adds the text entered in the input field to an unordered list as a list item. Each list item also contains an imag ...

Alternative form for non-javascript browsers in the absence of script

I'm currently working on a landing page for an upcoming product, and I've run into a bit of a snag. <form novalidate method="POST" class="subscribe-form"> <noscript> </form> <form method="POST" action="/ ...

Implementing div elements in a carousel of images

I've been working on an image slider that halts scrolling when the mouse hovers over it. However, I'd like to use div tags instead of image tags to create custom shapes within the slider using CSS. Does anyone have any advice on how to achieve th ...

Having trouble converting JSON object to regular object?

I'm trying to change a JSON object into a regular object by using this method... var slaobj = eval('('+s+')'); However, it doesn't appear to be working correctly (the `.length' is returning as undefined). What m ...

having difficulty uploading an image on wampserver

I am seeking advice and assistance with an issue I am facing. I am attempting to upload an image, but Wampserver keeps displaying the following error message (Warning: POST Content-Length of 80237 bytes exceeds the limit of 750 bytes in Unknown on line 0 F ...

Clearing the ng-model value in a controller following an ng-change event

Is there a way to reset the ng-model value in the controller after an ngChange event without needing to use a directive? <div ng-repeat="i in items"> <!-- Some DOM comes here --> <select ng-model="i.avail" ng-change="changeAvail(i. ...

EJS not displaying object values properly

I'm currently in the process of setting up a blog and I want to create a page that displays the titles of all the articles I've written. For example: List of Articles: * Title: Article 1 * Title: Article 2 * Title: Article 3 Below is my Schem ...

undefined reference to $

I'm currently working on a JavaScript project that involves using key events to display alphabets on the screen. However, I've encountered an error and need some assistance. <!DOCTYPE html> <html lang="en"> <head> <met ...

What is the best way to utilize AJAX to send a value from a foreach loop in Laravel?

I'm encountering an issue where all forms are sending the value as if it's from the first form, however, my intention is for each form to send the data inside it when I press the send button. Blade @foreach($car_lists as $car_list) <li class= ...

Enhancing navigation functionality using CSS

I have two separate pages with navigation included in both. This way, it's easier to edit the navigation menu once instead of doing so on each page individually. However, I am now facing uncertainty on how to implement the 'active' class usi ...

What could be the reason behind the malfunctioning of my media query in the

I am trying to connect an external stylesheet to my React component in order to apply different styles based on screen width. Specifically, when the screen width is less than 300px, I want the logo to have a height of 100vh. However, it seems that the medi ...

unable to reset contact form functionality

I need to implement a Contact Us form on my website. The form should clear the text fields after submission and display a Thank You message. Below is the HTML code: <div class="form"> <div id="sendmessage">Your message has been sent. Thank yo ...

The Node.js server is outputting an HTTP status code of 404

I have recently set up a small server. Interestingly, when I attempt to perform a GET request to my server through a browser, I can see the correct data. However, when I try to make a POST request to my server using code, I receive an HTTP status 404 error ...

What might be the reason for the absence of post data when sending it to a CodeIgniter controller through ajax

After going through numerous SO posts addressing the same issue and attempting all recommended solutions, I am still struggling to identify what I am doing incorrectly. Despite being able to log data up to the controller, the post data remains empty consis ...

I'm trying to set it up so that an image pops up when I hover over text. I've tried incorporating a few different JavaScripts, but I still can

I'm struggling to display an image on my website. I have the necessary code parts, but it's not working as expected. function showImage() { $('.img').addClass('display'); } function hideImage() { $('.img'). ...

Display the Image Element in Angular only when the image actually exists

In my HTML code, I have two sibling elements - one is an image and the other is a div. I want to display the image element if the image exists, and show the div element if the image doesn't exist. Here's how my elements are structured: <img ...

Creating a Conditional Structure in HTML: A Step-by-Step Guide

My website is in need of a form that can identify the user's role based on their name input. This feature is essential for individuals with private roles. Is it possible to achieve this using HTML alone, without relying on JavaScript? If not, what st ...

Tips for customizing the font color in Material UI Typography

Is it possible to change the color of only this text to red? return <Typography style={{ color: 'red' }}>Login Invalid</Typography> I came across this online solution, but I am unsure how to implement it as there is no theme={color ...

Coordinate the execution of two AJAX jQuery functions

There are two jQuery functions in my code, both making ajax calls with async: false property set. Each function redirects based on the response of the ajax call. However, the first function is not redirecting because the second function is not waiting for ...

Unable to apply the flex-grow property to a column flex box that has a specified minimum height

I am currently working on designing a website layout that harnesses the power of flexbox to fill the entire page with content, even when the content does not fully occupy the length of the page. My approach involves creating a large flexbox container with ...