How can I trigger a function after a 2-minute countdown in JavaScript?

I would like to confess right away that I am not an expert in Javascript! However, I do possess the knowledge of using ajax. Despite this, I am struggling with a particular issue and require some assistance.

My challenge is to create a 5-minute countdown and execute a function once the timer reaches zero. It is crucial for me to pass a variable to this function. Although I attempted to use SetInterval, it is definitely not my area of expertise. Is there anyone who could provide some guidance or suggestions? I can share the code I have so far, but let's just say a gorilla at a typewriter in the darkness best describes it!

Answer №1

You can try approaching it in this manner. Utilize the setTimeout() function to manage the timing aspect of the task, or in other words, to control the countdown displayed on the screen.

When initiating the setTimeout(), also initiate the function call using setInterval(). setInterval is helpful for triggering functions at specific time intervals, attempting to run them repeatedly. Once your function has executed, simply use clearInterval() to halt the timer.

Here is a code snippet borrowed and slightly adapted from a source, untested but should help you grasp the concept.

Countdown Timer: - Adapted from here.

<form name="counter"><input type="text" size="8"
name="d2"></form>

<script>
<!-- 
// 
 var interval="";
 var milisec=0;
 var seconds=300; 
 document.counter.d2.value='500';

function display(){ 
 if (milisec<=0){ 
    milisec=9;
    seconds-=1;
 } 
 if (seconds<=-1){ 
    milisec=0;
    seconds+=1; 
 } 
 else 
    milisec-=1;
    document.counter.d2.value=seconds+"."+milisec;
    setTimeout("display()",100);
    var interval = setInterval("goFunction(\" + seconds + \")", seconds);
} 
display();

goFunction(param)
{
   clearInterval(interval);
   // ... Perform necessary actions
}
-->
</script>

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

What is the reason behind the 'load' event handler not being triggered for an <applet>?

I need a function to run after an <applet> element finishes loading: // Create applet element var $applet = $("<applet></applet>"); // Attach event listener $applet.load(function() { alert('Applet has finished loading'); } ...

Focusing on the active element in Typescript

I am working on a section marked with the class 'concert-landing-synopsis' and I need to add a class to a different element when this section comes into focus during scrolling. Despite exploring various solutions, the focused variable always seem ...

Creating a Vue JS 3 Application that can smoothly operate on older versions of Firefox and Chrome

Currently, I am working on developing an application using VueJS 3, and everything seems to be functioning well on my local machine. However, I also need it to work smoothly on older browsers such as Firefox 38 and Chrome 49. The app utilizes various "fet ...

Display the list items within a div only if the height is lower than a separate div

I have a scenario where I have two divs named left and right. The left div contains a list of bullets (li elements) and is floated to the left, while the right div has text and HTML content. At times, either the left or the right div may be taller than the ...

Error: The function res.getHeader is not recognized within the Next.js API environment

I am currently working on a web application using NextJS 13, TypeScript, Next Auth v4, Prisma (using SQLite for development), and OpenAI. While accessing the API endpoint, I encountered an error in the console with the following message: error - TypeError ...

Having difficulty utilizing the express.session module in conjunction with HTTPS

I need to implement authentication and session creation on a HTTPS static website using expressjs. Here is the code snippet: app.js: // Set up the https server var express = require('express'); var https = require('https'); var http ...

The content of the snackbar message remains static and does not update dynamically

I am attempting to modify some data within a snackbar message, but the message does not seem to update. Here is a brief example of what I am trying to accomplish: https://stackblitz.com/edit/angular-snackbar-qvxipb?file=app%2Fapp.component.html Desired ...

Consistentize Column Titles in Uploaded Excel Spreadsheet

I have a friend who takes customer orders, and these customers are required to submit an excel sheet with specific fields such as item, description, brand, quantity, etc. However, the challenge arises when these sheets do not consistently use the same colu ...

Once a WordPress user includes a php file

For the past three days, I've been grappling with this issue... calling on all experts for assistance! I manage four distinct Wordpress membership sites, each with its own branding. My goal is simple - to have a .wav file play the plan's name wh ...

Navigating through the year selection with your keyboard

By default, a dropdown menu containing years allows for keyboard navigation. For example, if you type in 1992 while the dropdown is selected, it will automatically move to that specific year option. I am curious to know if there is a way to activate a two ...

I found myself in a bit of a predicament as I tried to transition a petite

Recently, I've been working on a small project that is built using pure HTML, CSS, and JavaScript. As I am delving into the realm of Vue.js, I decided to challenge myself by migrating this project to Vue.js. Here is how it currently functions with Ja ...

Holding off on routing the pathName through the router until the next-page-transitions have been completed

In my current setup, I have two distinct elements at play. Using the code snippet below: className={router.pathname.startsWith("/pagename") ? "menu-active" : ""} I am able to apply the menu-active class to the pagename naviga ...

A step-by-step guide to incorporating VeeValidate with vue-i18n

When a click event is triggered, I am able to change the language in vue-i18n. However, I am facing an issue with changing the vee-validate dictionary to match the same language. Main.js import VeeValidate from 'vee-validate' import validations ...

Send the useState function as a prop

I've encountered a challenge while attempting to pass a useState function named setState to a custom component. Despite several attempts, I have been unsuccessful in achieving the desired outcome. This is how I am invoking my custom component: const ...

AngularJS UI Router: Best Practices for Including the Controller Script

I have created a basic AngularJS single page application that uses UI Router to navigate between two views. When the user clicks on the Home link, they should see a line of text. Similarly, clicking on the About link should display some text as well, but i ...

How to send a JSON array to a Node.js cloud function

I've been attempting to convert a JavaScript object array into JSON in order to include it in a POST request to a cloud function. However, I keep encountering an error when using the JSON.parse() function - SyntaxError: Unexpected token u in JSON at p ...

To manipulate the array in a more complex manner, either add or remove the item based on its existence: if it's already in the array, remove it; if it

As I prepare to send key-value pairs to the backend in the form of a JSON structure, each representing a category (e.g., customer churn rate), I encounter an issue. The idea is to add checkmarked options to the array of their respective categories. However ...

Tips for removing all elements from an array using jQuery

let values=[]; values.push(data); I have decided to use an array to keep track of my data, and then send it via ajax. The first submission goes smoothly. However, on subsequent submissions, null values are also sent along with the actual data to the serv ...

What is the most efficient way to utilize a single Google Data Studio template across multiple accounts in a dynamic manner

I've been exploring different options on how to accomplish this: My dataset contains information on various clients, and I am interested in designing a custom Google Data Studio template for specific reports. Ideally, I would like the template to be ...

Node.js web server operating on port 3000 is running a script

I have developed a Node.js script that extracts data from a database and saves it in a file. Additionally, I have set up a Node.js web server listening on port 3000 using forever to keep it running constantly. However, the script currently lacks a web inte ...