The combination of setInterval() and if(confirm()) is not possible in pure JavaScript

One day, I encountered a simple if(confirm()) condition like this:

if(confirm('Some question')) {
    agreed_function();
} else {
    cancel_function();
}

function agreed_function() {
    console.log('OK');
}
function cancel_function() {
    console.log('Cancel');
}

Suddenly, I realized that I needed to call the cancel_function() not just when the "Cancel" button was clicked, but also if the "OK" button wasn't clicked within 3 seconds. It seemed like a challenge, so I started tinkering with my code.

Despite my efforts, the interval part of the code didn't work as intended. Here's what I had:

var interval = setInterval(function() {
    cancel_function();
}, 3000);

if(confirm('Some question')) {
    clearInterval(interval);
    agreed_function();
} else {
    clearInterval(interval); // prevent calling cancel_function() every 3 seconds
    cancel_function();
}

function agreed_function() {
    console.log('OK');
}
function cancel_function() {
    console.log('Cancel');
}

I found myself stuck, wondering how to overcome this obstacle. Any ideas on how to resolve this dilemma?

Answer №1

however, the interval isn't functioning properly

The reason for this is that alert boxes (including those created using confirm) pause the execution of the window.

As a result, your code halts until the user interacts with the alert box to close it. Unfortunately, there doesn't appear to be a way to programmatically dismiss these alert boxes, so you are stuck waiting for user action before your code can resume.

In the past, developers have handled this situation by crafting their own custom modals using popular UI libraries (such as JQuery's modal component) or building them from scratch, rather than relying on the default browser-generated ones like alert and confirm.


To put it simply, the presence of the alert box causes your code to pause, thus interfering with the functionality of the interval in your code.

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

Logging DOM elements with Electron's webview preload feature

Within my Electron program, I am utilizing a webview in my index.html file. The webview is equipped with a preloader, and my goal is to manipulate the DOM of the webview specifically, not just the index.html file. In my preloader code snippet below, the c ...

On page load, refresh the content of the div based on the selected radio button values

My goal is to automatically collect the values of checked radio buttons when the page loads, rather than waiting for a user interaction like clicking a radio button. Below is the JavaScript code I am using: $(function () { updateDivResult(); $(&a ...

Errors encountered while running `npm install discord.js`

I am currently facing an issue while trying to install discord.js. Unfortunately, I keep encountering the following errors: npm ERR! cb() never called! npm ERR! This is an error with npm itself. Please report this error at: npm ERR! <https://npm.co ...

Difficulty with Bootstrap 4 mobile navbar dropdown feature

<div class="baslik baslik1 baslik2 "> <nav class="navbar bg-light navbar-light navbar-expand-sm sticky-top "> <a href="./index.html" class="navbar-brand"><img src="img/512x512logo.png" ...

Utilize @db.Decimal within the Prisma framework for the parameters "s", "e", and "d"

When I define the schema in Prisma like this: value Decimal? @db.Decimal(7, 4) Why do I always get this format when retrieving the value from the database: "value": { "s": 1, "e": 0, & ...

Creating multiple div elements with changing content dynamically

I am facing an issue with a div named 'red' on my website where user messages overflow the 40px length of the div. To prevent this, I want to duplicate the 'red' div every time a message is sent so that the messages stay within the boun ...

Calculating the width of fluctuating DOM elements in AngularJS

It seems like most of my Angular questions are just me overlooking something really silly, so let's hope that's the case here too. Currently, I am working on a directive to manage the scrolling of a wide list of thumbnails. While it was working ...

Even in the face of errors, Selenium with Node.js continues to run seamlessly. The challenge arises specifically with the 107.xx version of the Chrome browser and Chrome driver

Currently, I am employed in a project involving NODE JS (javascript) with selenium webdriver. Package.json- “chai”: “^4.3.6”, “chromedriver”: “^107.0.3”, “geckodriver”: “^3.2.0”, “mocha”: “^10.0.0”, “mochawesome”: “^7. ...

Creating multi-dimensional arrays using array lists with Axios and Vue.js

My knowledge of axios and JavaScript is limited, and I find myself struggling with creating a multi-dimensional array. 1. This is how I want my data to be structured : https://i.stack.imgur.com/kboNU.png userList: [ { ...

Leverage ajax/js to dynamically refresh a single select tag within a set of multiple

While working on a project, I encountered a challenge while using JavaScript to update a <select> tag within a page. The specific issue arises because the page is designed in a management style with multiple forms generated dynamically through PHP ba ...

Singleton constructor running repeatedly in NextJS 13 middleware

I'm encountering an issue with a simple singleton called Paths: export default class Paths { private static _instance: Paths; private constructor() { console.log('paths constructor'); } public static get Instance() { consol ...

Performing a password-protected JavaScript Ajax request that includes special characters

Within my JavaScript page, I have implemented an Ajax call shown in the code snippet below. The PHP page resides within a corporate intranet that demands domain authentication (without basic auth). To extract the username (u) and password (p), I am using j ...

When running JavaScript from a .js.erb file, it gets executed while still being visible as plain text

I'm facing an issue with a form inside a popup window. Here's how it looks: <%= form_tag "/controller/action", :method => :get, :remote => true do %> ... <% end %> Within my controller: respond_to do |format| format.js end ...

Choose ng-change within the table

I've searched everywhere for an answer to this, but I couldn't find it. I have a table that contains select and date input fields. <table id="tblCorrAction" class="table table-bordered table-striped table-hover table-condensed"> <t ...

Display four unique automobile insignias using Webcomponent/Stencil.js

Exploring Web Components and Stencil.js for the first time, I'm currently developing an application that offers detailed car information based on the user's selection of car type. The challenge I'm facing involves displaying four different l ...

Display overlay objects specifically focused around the mouse cursor, regardless of its position on the screen

I am currently working on a project using SVG files and processing.js to develop a unique homepage that incorporates both animation and static elements. The concept is to maintain the overall structure of the original homepage but with varying colors, esse ...

Fetching data using ajax and then appending it to the webpage

I am currently loading content from a PHP file in JSON format. products.php <?php $stmt = $mysqli->prepare("SELECT * FROM products LIMIT 10"); $stmt->execute(); $products = $stmt->get_result(); $produc ...

Compiling modal window content in AngularJS can lead to the creation of controllers that are left disconnected

I implemented a modal window triggered by fancybox in my project. Once the modal is displayed, fancybox triggers a "modalShown" event that is listened for by AppController. In this listener, $compile is called on the modal content to create the ModalContro ...

Building a React.js application and fetching information with Ajax

In my quest to create a high-speed React.js application that functions as a game, I find myself in need of displaying real-time data. However, the traditional method of loading this data from the server using Ajax doesn't quite align with the reactive ...

Ways to abbreviate a URL using Next JS

While working on my Next.js application, I encountered an issue with passing an object between pages. To achieve this, I compressed my array of objects into JSON using JSON.stringify(result) on the index page and then parsed it on the second page using JSO ...