Prevent alert() from halting the execution of JavaScript - javascript

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?

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.

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

Related

MVC call Javascript from razor #Helper at unpredictable times

In my MVC view I need to get razor c# code to execute a javascript function at unpredictable times, way after the page has loaded.
I have used a thread to simulate unpredictableness but ultimately instead of the thread it will be a WCF callback method that raises an event which runs the helper, but to eliminate session issues I have used the thread.
Javascript to execute:
<script type="text/javascript">
function DisplayNews(news) {
alert(news);
}
</script>
Helper that runs the javascript (because sticking this directly in the below thread didn't work)
#helper UpdateNews(string news)
{
<script>
DisplayNews(news);
</script>
}
Thread that simulates unpredictableness/post page loading or non user invoked events
#{
System.Threading.Thread T = new System.Threading.Thread(new System.Threading.ThreadStart(delegate
{
while (true)
{
System.Threading.Thread.Sleep(5000);
UpdateNews("Some cool news");
}
}));
T.Start();
}
If I stick a break point at UpdateNews("Some cool news"); I can see that it gets hit every 5 seconds as it should, but thats as far as it gets, nothing else happens. I can't stick a break point in the helper or the Javascript so I can't see where it stops working after that.
Is this going to work at all or is there another way I should be approaching this?
Any help would be greatly appreciated.
In server side code you can call an client function...
Razor executed in server side and javascript is in client side.that mean when you get server response it's created by razor code in server side and now you can just use javascript in client side
I may be misunderstanding what you are trying to do but you can have javascript that will run on page load that will be wrapped in a set timeout with a random millisecond period.
Something like this:
<script>
window.onload = function() {
setTimeout(function() {}, 1000); // this will run 1 second after page load
}
</script>
simply randomize the number being passed as the second parameter to setTimeout and your javascript will run at a random time after the page loads.

Running JS in a killable 'thread'; detecting and canceling long-running processes

Summary: How can I execute a JavaScript function, but then "execute" (kill) it if it does not finish with a timeframe (e.g. 2 seconds)?
Details
I'm writing a web application for interactively writing and testing PEG grammars. Unfortunately, the JavaScript library I'm using for parsing using a PEG has a 'bug' where certain poorly-written or unfinished grammars cause infinite execution (not even detected by some browsers). You can be happily typing along, working on your grammar, when suddenly the browser locks up and you lose all your hard work.
Right now my code is (very simplified):
grammarTextarea.onchange = generateParserAndThenParseInputAndThenUpdateThePage;
I'd like to change it to something like:
grammarTextarea.onchange = function(){
var result = runTimeLimited( generateParserAndThenParseInput, 2000 );
if (result) updateThePage();
};
I've considered using an iframe or other tab/window to execute the content, but even this messy solution is not guaranteed to work in the latest versions of major browsers. However, I'm happy to accept a solution that works only in latest versions of Safari, Chrome, and Firefox.
Web workers provide this capability—as long as the long-running function does not require access to the window or document or closures—albeit in a somewhat-cumbersome manner. Here's the solution I ended up with:
main.js
var worker, activeMsgs, userTypingTimeout, deathRowTimer;
killWorker(); // Also creates the first one
grammarTextarea.onchange = grammarTextarea.oninput = function(){
// Wait until the user has not typed for 500ms before parsing
clearTimeout(userTypingTimeout);
userTypingTimeout = setTimeout(askWorkerToParse,500);
}
function askWorkerToParse(){
worker.postMessage({action:'parseInput',input:grammarTextarea.value});
activeMsgs++; // Another message is in flight
clearTimeout(deathRowTimer); // Restart the timer
deathRowTimer = setTimeout(killWorker,2000); // It must finish quickly
};
function killWorker(){
if (worker) worker.terminate(); // This kills the thread
worker = new Worker('worker.js') // Create a new worker thread
activeMsgs = 0; // No messages are pending on this new one
worker.addEventListener('message',handleWorkerResponse,false);
}
function handleWorkerResponse(evt){
// If this is the last message, it responded in time: it gets to live.
if (--activeMsgs==0) clearTimeout(deathRowTimer);
// **Process the evt.data.results from the worker**
},false);
worker.js
importScripts('utils.js') // Each worker is a blank slate; must load libs
self.addEventListener('message',function(evt){
var data = evt.data;
switch(data.action){
case 'parseInput':
// Actually do the work (which sometimes goes bad and locks up)
var parseResults = parse(data.input);
// Send the results back to the main thread.
self.postMessage({kind:'parse-results',results:parseResults});
break;
}
},false);

closing the current tab in a chrome extention

I am writing a chrome extension that when clicked, will close the current tab after a given amount of time.
I am sending a message with the time, from popup.js to background.js. But the tab won't close.
The alert works when I uncomment it, so it seems to be just the remove line. I assume it's something about tab.id.
chrome.extension.onMessage.addListener(
function message(request, sender, callback) {
var ctr = 0;
ctr = parseInt(request.text, 10);
setTimeout(function() {
chrome.tabs.getCurrent(function(tab) {
//window.alert("Working?");
chrome.tabs.remove(tab.id, function(){});
});
}, ctr);
}
);
1.
chrome.extension has no onMessage event. I assume you mean the correct chrome.runtime.onMessage
2.
You have probably misunderstood(*) the purpose of chrome.tabs.getCurrent:
Gets the tab that this script call is being made from. May be undefined if called from a non-tab context (for example: a background page or popup view).
Since, you are calling it from a non-tab context (namely the background page), tab will be undefined.
(*): "misunderstood" as in "not bother to read the manual"...
3.
It is not clear if you want to close the active tab at the moment the timer is set or at the moment it is triggered. (In your code, you are attempting to do the latter, although the former would make more sense to me.)
The correct way to do it:
chrome.runtime.onMessage.addListener(function message(msg) {
var ctr = 0;
ctr = parseInt(msg.text, 10);
setTimeout(function() {
chrome.tabs.query({ active: true }, function(tabs) {
chrome.tabs.remove(tabs[0].id);
});
}, ctr);
});
Also, note that using functions like setTimeout and setInteval will only work reliably in persistent background pages (but not in event pages). If possible, you are advised to migrate to event pages (which are more "resource-friendly"), in which case you will also have to switch to the alarms API.

javascript browser timeout second timer

I am trying to set a session timeout with Javascript and looks like the alert is blocking the timer from starting. Here is my code:
var first_timer = 2 * 1000;
var second_timer = 8 * 1000;
var down = -1;
function initTimer() {
down = setTimeout(processTimeout, first_timer)
}
function processTimeout() {
down = setTimeout(logout, second_timer);
alert ("Timeout of first timer, timerid:" + down );
}
function logout() {
alert("You are logged out");
window.location = "http://www.google.com"
}
function clearTimer() {
if ( -1 != down )
clearTimeout(down);
alert("Restarting timer");
initTimer();
}
initTimer();
When I run the above, I see the second timer only starts after the first alert is dismissed. How can I make sure the second timer starts immediately after first timeout even if the alert is not dismissed?
Thx
The alert() function blocks everything else until it is dismissed. You can use whats known as a modal dialog to create your own alert style message that does not block.
jQuery UI has this feature.
It most probably depends on the browser you are using. I'm not experiencing the issue you describe with latest Firefox.
But still, the second timer alert box won't be shown until the first one is closed.
This is because JavaScript interpreters are not multi-threaded. But JavaScript itself is heavily asynchronous, especially on long delay requests such as timers, AJAX and animations. This is what sometimes gives the feeling of multi-threading.
Indeed, in your code sample, the second timer started as expected. When I dismiss the first dialog box, let's say, 10 sec after it appears, the second one is immediately shown.
Nonetheless, and it may be your question, it will never be shown before you dismiss the first alert because alert is a synchronous call. So that the main event loop won't get the control back until dismissed.
A workaround for this situation is to use "HTML" dialog boxes as those provide by Jquery-UI for example.

what type of timer does this site use?

me and my team really working on a site like www.bidrivals.com/us (penny auction site)
i browse it codes
found
<div class="timer online">
<div class="text">00:00:03</div>
</div>
i could not found anything on the js file of this site ...
can any body tell me which type of js timer that this site is using?
any example code for that?
anything available like this in j query or prototype framework ?
Javascript provides the setTimeout and setInterval functions to run actions at a "set time" in milliseconds.
https://developer.mozilla.org/en/DOM/window.setTimeout
https://developer.mozilla.org/en/window.setInterval
Example:
// this is will act like a counter on the page
var t = 0,
div = document.createElement('div');
div.innerHTML = t;
document.body.appendChild(div);
setInterval(function () {
t += 1;
div.innerHTML = t;
}, 1000); // this will run once every second
In the case of this website, they run an XHR request every second to get the data for each bid. Checkout the console to see the requests.
there is a server side count, to control the hits and time.
check $.post in jquery, in this case you call an server side script who inform webpage the times, and the bid actions... once with this data, you change de div values with callback function.
check the network requests using firebug, you will see a json coming from a getData webpage.

Categories

Resources