3

I have the following simple if(confirm()) condition like

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

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

Now I need calling of the cancel_function() not only if we click the "Cancel" button, but if there is no clicking by the "OK" button after a while for example after 3 seconds. So if we click "OK" during 3 seconds, the cancel_function() won't be called.

So here is my code where only the if(confirm()) works, but the interval doesn't

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

if(confirm('Some question')) {
    clearInterval(interval);
    agreed_function();
} else {
    clearInterval(interval); // not to call the cancel_function() every 3 seconds
    cancel_function();
}

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

How to resolve the problem?

stckvrw
  • 1,689
  • 18
  • 42
  • You have posted a bunch of code & some explanation of it; you haven't actually asked a question. – Scott Hunter Sep 13 '19 at 19:43
  • 5
    yes you are correct. `confirm` is blocking. If you want to implement a non-blocking confirmation so that you can use `setInterval` to clear it, then you need to use JavaScript to display a modal dialog instead. Preferably a JavaScript UI framework like jquery, React, Angular, etc. – Brandon Sep 13 '19 at 19:44

1 Answers1

4

but the interval doesn't [work]

This is because alert boxes (including ones created from confirm) block the execution on the window.

This means your code stops running until the alert box is closed. Unfortunately, there doesn't seem to be a way to close these alert boxes programmatically, so you'd have to wait for the user to interact with it before your code can continue.

Historically, developers handle these kinds of things by creating their own custom models with the help of popular UI libraries (e.g. JQuery has a model component) or from scratch, and not using the browser level ones generated by alert and confirm.


But to answer your question simply, your code stops running because of the alert box, so that's why the interval doesn't work as expected.

Nick Zuber
  • 5,467
  • 3
  • 24
  • 48