1

First of all , i know that JavaScript is single threaded. Lets say i have a counter that outputs its values every second.

var counter = 0;
setInterval(function(){
        console.log("Interval:  " + ++counter);

    }, 1000);

At some point, i want to trigger some code that halts the execution of the script. For example, an alert message.

setTimeout(function(){
    alert("Some alert message");
},10000);

At this point when the alert message popped, the interval code will halt. Is there a trick so it will not stop executing?

Vandervidi
  • 642
  • 2
  • 14
  • 32
  • 6
    Don't use an alert, plenty of notification frameworks out there. – epascarello Oct 18 '15 at 20:56
  • 1
    no trick...just don't use it – charlietfl Oct 18 '15 at 20:57
  • 3
    Interestingly, I found [in the spec](http://www.w3.org/html/wg/drafts/html/master/webappapis.html#dom-alert) a couple of days ago that the pausing of the execution is only "optional" - see step 7. – James Thorpe Oct 18 '15 at 20:57
  • Instead of alert, un-hide some HTML element on the page. – Paul Kienitz Oct 18 '15 at 21:03
  • Since you aren't describing wht you are really trying to accomplish, I don't know if will be helpful, however you might look at the Web Worker specification. It may be a solution as it allows for creating additional execution threads, although there are real limitations. Note - I don't know if `alert` will block all threads spawned via the parent window, and I'm in no mood to work up a test for an abstract question. – barry-johnson Oct 18 '15 at 21:04
  • 1
    To be clear: while alert() is shown the interval is rather "paused" and will continue after modal prompt is closed. Your question implies you'd like to have interval running "in the backround" of the prompt, is it correct? – myf Oct 18 '15 at 21:21
  • @myf exactly. to all the comments saying "dont use alert()" , it is just an example for a code that blocks the execution.. – Vandervidi Oct 18 '15 at 21:23
  • Do not rely on an `alert` pausing invocation. This cannot be guaranteed. If you want to stop your interval, use `clearInterval`. Also, as others have suggested, consider a non-UX-breaking method of displaying the data too, e.g. a styled `
    ` with fixed positioning
    – Paul S. Oct 18 '15 at 21:44
  • @JamesThorpe Optional to browser implementation, not to the API. All browsers I know chose the blocking option. – Tomáš Zato Oct 18 '15 at 22:19
  • @TomášZato indeed - I've never seen a non blocking implementation either, was just something I came across in the spec that I thought was interesting! – James Thorpe Oct 19 '15 at 05:45

2 Answers2

2

Depending on the browsers you need to support (check browser compatibility), you could use WebWorkers to execute scripts in parallel threads. You just need to split up your code into separate files, so that the code, which is to run in a worker thread, is in its own file. Adjusting your example without going into details of the worker you could set up a file worker.js containing the following code:

// file worker.js
var counter = 0;
setInterval(function(){
        console.log("Interval:  " + ++counter);

        // The worker will live until you kill it.
        if (counter > 100) self.close();  
}, 1000);

Your main JavaScript file will then set up the new worker to have it run in a separate worker thread.

// Set up the new worker in a separate thread.
var worker = new Worker("worker.js");

setTimeout(function(){
    // This will not stop the worker from logging to console.
    alert("Some alert message");
},10000);

Thus, the alert() in the main thread will not stop the execution of the worker thread, which will continue logging to console.

See this Plunk for a live demo.

altocumulus
  • 21,179
  • 13
  • 61
  • 84
1

First of all: Are you aware that if the code doesn't halt, the popups will stack on screen to infinity?

Alert is primarily used for simple web pages and debug purposes (it's the simplest breakpoint there is). If you want to notify the user on our site, use some framework or just make HTML popup. I just recently needed this and downloaded Jquery UI framework. I'm not the kind of guy who uses jQuery everywhere for everything, but getting HTML popups align nicely in browser is boring and tedious.

In JQuery UI you just do:

HTML:

<div id="my-dialog">Interval: <span id="counter">0</span></div>

JavaScript:

// Configure the div as dialog, call this only once
$("#my-dialog").dialog({modal:true,
                        autoOpen: false,
                        buttons: {
                          Ok: function() {
                            $( this ).dialog( "close" );
                          }
                        }
});
var counter = 0;

var intervalID = setInterval(function() {
  // Update counter info
  $("#count").html(++counter);
  // Show dialog
  $("#my-dialog").dialog("open");

}, 1000);

Demo

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
  • Sorry but you completely misunderstood my question. I am not looking for an alternative for alert. Im looking for a solution for using alert() and in the same time preventing it from halting the execution of the code. – Vandervidi Oct 18 '15 at 21:56
  • @VanderVidi Alert is a blocking function. Without starting another thread, you can't prevent it from halting code. Only other option apart from my proposal is, that you execute all your code in `WebWorker` thread and show `alerts` in UI thread. I understood your question completely, but you are still failing to understand the nature of `alert`. – Tomáš Zato Oct 18 '15 at 22:03
  • `using alert() and in the same time preventing it from halting the execution of the code` = use alert alternative or different programming language. – Tomáš Zato Oct 18 '15 at 22:04
  • WebWorker is what i was looking for. – Vandervidi Oct 18 '15 at 22:19
  • @VanderVidi Suprising. I will not update my answer though, if you need help with web workers, ask another question. I highly approve that you're gonna use them, because they make site way more responsive to UI events. – Tomáš Zato Oct 18 '15 at 22:22