Create a JavaScript function that continues to execute even after a button has been clicked

Although it may seem like simple logic, I am currently unable to log in. Imagine I have a function called mytimer() stored in a common file that is linked to every HTML page.

mytimer(){...........................};

Now, at some point on another page, when a specific condition is met, I want this mytimer() function to start running and continue for a set period. How can I achieve this? Any suggestions are welcome.
Thanks in advance!

Javascript code snippet:

// Set the date we're counting down to
var countDownDate = new Date(<?=$date?>).getTime();

var countdown = document.getElementById("tiles"); // get tag element

getCountdown();

var x = setInterval(function() {
  getCountdown();
}, 1000);

function getCountdown() {

  var now = new Date().getTime();

  var distance = countDownDate - now;

  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);
  countdown.innerHTML = "<span>" + days + "</span><span>" + hours + "</span><span>" + minutes + "</span><span>" + seconds + "</span>";
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("countdown").innerHTML = "EXPIRED";
    forever = false;
  }
}

function pad(n) {
  return (n < 10 ? '0' : '') + n;
}

function accept() {
  var id = document.getElementById("acceptbtn").getAttribute("data-id");

  var xhr = new XMLHttpRequest();
  xhr.onload = function() {
    if (this.readyState === 4 && this.status === 200) {
      console.log(this.responseText);
    }
  }

  xhr.open("GET", "ajax/acceptproduct.php?aid=" + id, true);
  xhr.send();
  alert(id);
}
<div id="countdown">
  <div id='tiles'></div>
  <div class="labels">
    <li>Days</li>
    <li>Hours</li>
    <li>Mins</li>
    <li>Secs</li>
  </div>
</div>

Answer №1

One possible solution is to employ the method of recursion.

const DELAY_TIME = 1000

let continueRunning = true;

function performAction() {


    // Add your specific logic here - you can set continueRunning to false to halt the process



    if (continueRunning) {
        setTimeout(performAction, DELAY_TIME);
    }
}

performAction();

Answer №2

If you're looking to incorporate a delay in your JavaScript code, using the window.setTimeout function is the way to go.

let timer;

function doSomething() {
    // Execute tasks

    // Set a timeout to call the function again
    timer = setTimeout(doSomething, 3000);
}

// Use this function to stop the loop whenever necessary
function stopFunction() {
    clearTimeout(timer);
}

For further information, feel free to visit:

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

Tips for regularly retrieving information from a psql table

I have a scenario where I am retrieving data from a psql table and converting it into a JSON array to be used for displaying a time series chart using JavaScript. The data that is passed needs to be in the form of an array. Since the data in the table get ...

Filter JavaScript elements by conditions and true/false values

I can't quite recall the answer to this at the moment. Consider an array of Vendors (this is just placeholder data): [ { "user_updated": null, "user_created": "128a84b5-275c-4f00-942e-e8ba6d85c60e", "d ...

The Google Chrome console is failing to display the accurate line numbers for JavaScript errors

Currently, I find myself grappling with debugging in an angular project built with ionic framework. Utilizing ion-router-outlet, I attempt to troubleshoot using the Google Chrome console. Unfortunately, the console is displaying inaccurate line numbers mak ...

Skipping an iteration in ng-repeat in Angular 1.0.8: A simple guide

Is it possible to skip a particular iteration in ng-repeat without modifying the underlying array/object being iterated over? Consider the following example: var steps = [ { enabled: true }, { enabled: true }, { ...

Is it possible to include multiple API routes within a single file in NextJS's Pages directory?

Currently learning NextJS and delving into the API. Within the api folder, there is a default hello.js file containing an export default function that outputs a JSON response. If I decide to include another route, do I need to create a new file for it or ...

What occurs when there are conflicting export names in Meteor?

After researching, I discovered that in Meteor, If your app utilizes the email package (and only if it uses the email package!) then your app can access Email and you can invoke Email.send. While most packages typically have just one export, there a ...

Unexpected outcome from the zero-fill operator (>>>) in Javascript's right shift operation

Initially, is (-1 >>> 0) === (2**32 - 1) possibly due to extending the number with a zero on the left, transforming it into a 33-bit number? However, why does (-1 >>> 32) === (2**32 - 1) as well? I had anticipated that after shifting the ...

What could be causing the error "Unexpected identifier 'trytoCatch' while trying to minify?

I recently updated my script.js and now I'm looking to use "minify" in Node.js to compress it. When I type the command minify script.js > script.min.js into the terminal, I get an error message that says: /node_modules/bin/minify.js:3 import "tryTo ...

An onClick event is triggered only after being clicked twice

It seems that the onClick event is not firing on the first click, but only works when clicked twice. The action this.props.PostLike(id) gets triggered with a delay of one click. How can I ensure it works correctly with just one click? The heart state togg ...

Updating the ID's of nested elements in JavaScript when duplicating an element

After a fruitless search on Google, I have turned to the experts on SO for assistance. The challenge: Create a duplicate of a dropdown menu and an input field with the click of a button (which can be done multiple times) The proposed solution: Implement ...

How can I replay an HTML audio element?

I created an HTML5 page with an audio element for playing music in mp3 format. However, when the music plays to the end, it stops and I'm using JavaScript to control the audio element. Even so, I can't seem to replay it, only stop it. Is there a ...

Exploring the power of nested routes in React Router 4: accessing /admin and / simultaneously

I'm encountering an issue with nested routing. The URLs on my normal site are different from those on the /admin page, and they have separate designs and HTML. I set up this sample routing, but whenever I refresh the page, it turns white without any ...

Using Javascript to Treat an HTML Document as a String

Check out the complete project on GitHub: https://github.com/sosophia10/TimeCapsule (refer to js/experience.js) I'm utilizing JQuery to develop "applications" for my website. I'm encountering a problem where I can't locate the correct synta ...

How can I organize the selected options from a select2 form element using a basic sorting method?

I am utilizing select2 by ivaynberg and encountering an issue with the data arrangement upon submission. Is there a method to have the results in the form submit data reflect the order in which they were selected in the select2 element, without relying on ...

Discovering methods to store browser credentials securely in jQuery

I need to prevent the login button from being enabled when either the username or password fields are empty. Check out the code snippet below: $(document).ready(function(){ $('input').on('keyup blur mouseenter', function(e) { ...

Is there a way to remove a value from the search bar while updating the table at the same time?

Although I can successfully search the table based on the values in my search bar, I am having trouble with updating the state when deleting a value. To see my code in action, check out my sandbox here. ...

Extracting data from XML using my custom script

I attempted to extract a specific value from an XML feed, but encountered some difficulties. In addition to the existing functionality that is working fine, I want to retrieve the value of "StartTime" as well. Here is the relevant section of the XML: < ...

How can I rectify the varying vulnerabilities that arise from npm installation?

After running npm audit, I encountered an error related to Uncontrolled Resource Consumption in firebase. Is there a solution available? The issue can be fixed using `npm audit fix --force`. This will install <a href="/cdn-cgi/l/email-protection" clas ...

Refresh my website's specific table automatically whenever the database is updated. Alternatively, reload the table every 2 seconds to ensure the latest values from the database are displayed

How can I update table values in real-time when the database in phpMyAdmin is updated? I have implemented some code that successfully updates the data on my webpage, but the issue is that the entire page reloads every 2 seconds. Is there a way to only ...

Leveraging the power of map in an Angular typescript file

I've been attempting to populate a Map in Angular by setting values dynamically. When certain buttons are clicked, the onClick function is invoked. typeArray: Map<number,string>; Rent(movieId: number){ this.typeArray.set(movieId,"Rental ...