execute function with new process like using new thread in java - javascript

is there any way to create new process and make it execute some code while main process execute some code too.
in my code,i used something like this:
<script>
function f1(){//some code
}
setTimeout(f1,delay);
</script>
my question is: the main process execute f1 function or a new one?,and if it is the main how can i execute f1 function with a new process.
i had tried setTimeout function and i see that the main process execute the function after a delay time.
any help please.

Threads and processes are two different things.
Until recently JavaScript had neither. You could emulate multi-threading using a timeout of 0. You can still do that.
For true multi-threading now you can use Web Workers. I don't think you can have multiple process except if you are using some plugin (Java Applets for example).
Just search in Wikipedia for thread, process and WebWorkers.

Related

How to call a function in WebView Javascript from Android Java without delay?

When using this method to call javascript functions there is a few millisecond delay (10ms - 50ms) in callback
webView.evaluateJavascript("javascript: updateARObject()", callback);
How to call a function instantaneously in javascript, all files are in asset folder of Android.
Is it possible with some custom WebView like Xwalkview?
Or socket connection between both?
ARCore is communicating with Three.js in real time, How to achieve that?
The reason the callback is present is because it cannot be done instantaneously from android app.
The main reason for that is that Android uses WebView to run javascript. Modern Android WebView is just an instance of Google Chrome wrapped in android view. As you understand this instance needs to be run on separate process as it does. If one chooses to dig deep he will find out that the communication between android app and WebView is done via AIDL service as all the interprocess communications should be done in android.
Taking into consideration the time needed to write an AIDL call into stack allocate memory and form message(main AIDL method of communication), send it, unwrap in Chrome, parse, execute javascript and do all this operations one more in order to answer - 10ms - 50ms is very low latency.
Maybe ArCore has its own its own js processor to handle js files fast. Or Google Chrome has its own method to communicate with ArCore(or inner instance). I don't know that - but it is Google developed products - I think they know their shortcuts.
Custom WebView may work - the only thing is that basically it will be a new version of browser you will need to support your js for it separately from all the other browsers due to a whole bunch of possible reasons.
Hope it helps you somehow.
From kitkat onwards use evaluateJavascript method instead loadUrl to call the javascript functions like below :
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript("enable();", null);
} else {
webView.loadUrl("javascript:enable();");
}
you can Use function call delay by setting :
window.setTimeout(function () { ... })
But ,It won't necessarily run right away, neither will explicitly setting the delay. If you will use setTimeout, it removes the function from the execution queue and it will only be invoked after JavaScript has finished with the current execution queue.
console.log(1);
setTimeout(function() {console.log(2)});
console.log(3);
console.log(4);
console.log(5);
//console logs 1,3,4,5,2
for more details see http://javascriptweblog.wordpress.com/2010/06/28/understanding-javascript-timers/
Hope, you'll find your answer. Cheers!

How to call C# code triggered by some JavaScript event with the help of Selenium webdriver?

I've Googled about this problem but could not find any questions about this (the inverse direction - execute JavaScript code - is of course more common).
If I remember correctly, there is some support to do this by using some .NET WebBrowser or WebView control.
Please note that triggering the code from some JavaScript event means the source of action flow is not from C# code as the following does:
var someResult = driver.ExecuteAsyncScript("var cb=arguments[0]; cb(someJsVariable);");
Here you can clearly see that the callback cb is executed inside JavaScript environment and looks really like that it flows and continues to run in the C# environment. However it's obvious the source of the entire flow is started from inside C# code (by the call driver.ExecuteAsyncScript).
My scenario is completely different. I want some kind of JavaScript code executing by any event inside JavaScript environment (e.g: document.onload, button.onclick, ...) and actually here I want to intercept the ajaxSend (of course this can be triggered by any action started inside the JavaScript environment) to send back the request options to C# environment.
So there should be some C# callback for the JavaScript code to call, something like this:
driver.ExecuteScript("$(document).ajaxSend(function(e,jXhr,options){ /* somehow trigger C# callback here to send back the options */ });");
If this cannot be done, I think Selenium should add this capability in future, it's a shame that a simple WebBrowser control can do this whereas a powerful WebDriver cannot.

Javascript: How to write a function that will be executed asynchronously?

I have a few lines of code that I want to run asynchronously in Javascript so that it doesn't slow down my main algorithm. See this pseudo code:
//main algorithm with critical code that should run as soon as possible
...
...
runInParallel(function(){
//time consuming unimportant code to shows some progress feedback to user
...
}
//the rest of the time critical algorithm
...
...
runInParallel(function(){
//time consuming unimportant code to shows some progress feedback to user
...
}
//and so on and so forth
I searched Stackoverflow for how to write asynchronous code in Javascript but the following questions are not similar to mine:
how to run a javascript function asynchronously, without using setTimeout?: it's about server side
Loading javascript asynchronously - How to do callbacks?: it's about loading source code
I guess I can use timers for this purpose. All I want is the body of the function runInParallel() that runs a code efficiently in parallel with my main algorithm with lower priority if possible. Anyone?
Javascript has no synchronization / thread management. If you wish to execute something asynchronously, you can use setTimeout combined with a callback to be notified when the function 's finished.
var asyncHandle = setTimeout(function () { asyncCode(); callback(); }, 10);
The asyncHandle can be used to cancel the timeout prior to the function being called.
If you're targeting HTML5 supporting browsers, go with HTML5 Web Workers.
You can also try this interesting, but quite old JavaScript compiler that allows a language extension for this purpose.

Is JavaScript multithreaded?

Here's my issue - I need to dynamically download several scripts using jQuery.getScript() and execute certain JavaScript code after all the scripts were loaded, so my plan was to do something like this:
function GetScripts(scripts, callback)
{
var len = scripts.length
for (var i in scripts)
{
jQuery.getScript(scripts[i], function()
{
len --;
// executing callback function if this is the last script that loaded
if (len == 0)
callback()
})
}
}
This will only work reliably if we assume that script.onload events for each script fire and execute sequentially and synchronously, so there would never be a situation when two or more of the event handlers would pass check for (len == 0) and execute callback method.
So my question - is that assumption correct and if not, what's the way to achieve what I am trying to do?
No, JavaScript is not multi-threaded. It is event driven and your assumption of the events firing sequentially (assuming they load sequentially) is what you will see. Your current implementation appears correct. I believe jQuery's .getScript() injects a new <script> tag, which should also force them to load in the correct order.
Currently JavaScript is not multithreaded, but the things will change in near future. There is a new thing in HTML5 called Worker. It allows you to do some job in background.
But it's currently is not supported by all browsers.
The JavaScript (ECMAScript) specification does not define any threading or synchronization mechanisms.
Moreover, the JavaScript engines in our browsers are deliberately single-threaded, in part because allowing more than one UI thread to operate concurrently would open an enormous can of worms. So your assumption and implementation are correct.
As a sidenote, another commenter alluded to the fact that any JavaScriptengine vendor could add threading and synchronization features, or a vendor could enable users to implement those features themselves, as described in this article: Multi-threaded JavaScript?
JavaScript is absolutely not multithreaded - you have a guarantee that any handler you use will not be interrupted by another event. Any other events, like mouse clicks, XMLHttpRequest returns, and timers will queue up while your code is executing, and run one after another.
No, all the browsers give you only one thread for JavaScript.
To be clear, the browser JS implementation is not multithreaded.
The language, JS, can be multi-threaded.
The question does not apply here however.
What applies is that getScript() is asynchronous (returns immediately and get's queued), however, the browser will execute DOM attached <script> content sequentially so your dependent JS code will see them loaded sequentially. This is a browser feature and not dependent on the JS threading or the getScript() call.
If getScript() retrieved scripts with xmlHTTPRequest, setTimeout(), websockets or any other async call then your scripts would not be guaranteed to execute in order. However, your callback would still get called after all scripts execute since the execution context of your 'len' variable is in a closure which persists it's context through asynchronous invocations of your function.
JS in general is single threaded. However HTML5 Web workers introduce multi-threading. Read more at http://www.html5rocks.com/en/tutorials/workers/basics/
Thought it might be interesting to try this out with a "forced", delayed script delivery ...
added two available scripts from
google
added delayjs.php as the 2nd
array element. delayjs.php sleeps
for 5 seconds before delivering an empty js
object.
added a callback that
"verifies" the existence of the
expected objects from the script
files.
added a few js commands that
are executed on the line after the
GetScripts() call, to "test" sequential js commands.
The result with the script load is as expected; the callback is triggered only after the last script has loaded. What surprised me was that the js commands that followed the GetScripts() call triggered without the need to wait for the last script to load. I was under the impression that no js commands would be executed while the browser was waiting on a js script to load ...
var scripts = [];
scripts.push('http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js');
scripts.push('http://localhost/delayjs.php');
scripts.push('http://ajax.googleapis.com/ajax/libs/scriptaculous/1.8.3/scriptaculous.js');
function logem() {
console.log(typeof Prototype);
console.log(typeof Scriptaculous);
console.log(typeof delayedjs);
}
GetScripts( scripts, logem );
console.log('Try to do something before GetScripts finishes.\n');
$('#testdiv').text('test content');
<?php
sleep(5);
echo 'var delayedjs = {};';
You can probably get some kind of multithreadedness if you create a number of frames in an HTML document, and run a script in each of them, each calling a function in the main frame that should make sense of the results of those functions.

jQuery profiling - measure complete onReady runtime

I'd like to measure how long it takes to run the whole $().ready() scope in each of page.
For profiling specific functions I just set a new Date() variable at the beginning of the relevant part and then check how long it takes to get to the end of the relevant part.
The problem with measuring the whole $().ready scope is that it can sometimes run some of the code asynchronously and then I can not wait for it all to finish and see how long it has taken.
Is there any event which is fired once the page has completely finished running all $().ready code?
EDIT: Using Firebug or other client debuggers are not an option since I also need to collect this profiling information from website users for monitoring and graphing our web site's page load speeds
Thanks!
There will be no event fired because its virtually impossible for ready() to know when any asynchronous functions are done processing. Thus, you'll need to bake this functionality in yourself; you could use jQuery's custom events, or perhaps set a function to run on setInterval() that can introspect the environment and deduce whether or not everything else is done.
Swap out the jQuery ready function with a function that does your start and finish tracking, and calls the original method.
jQuery.ready = (function() {
var original = jQuery.ready;
return function() {
alert('starting profiler');
original();
alert('ending profiler');
};
})();
$(function() {
alert('this message will appear between the profiler messages above...');
});
Have you tried using Profiler in Firebug?

Categories