What is this timeout-related feature of javascript called? - javascript

I'm familiar with this behavior, but don't have the vocabulary to describe (and thus google) it.
setTimeout(function () { alert("timeout!"); }, 1000);
veryLongProcess(); // lasts longer than 1000 milliseconds
I believe the result of this is that you get your alert after the long process is finished, i.e. longer than 1 second after the code was executed. I imagine this as timeouts sending functions to some separate "thread" or "stack" or "cycle" that can only start after the current one is finished, even if that current one takes longer than the timeout was originally specified for.
Is there a name for this? How can I learn more about how it works?

I believe you may be looking for the term 'synchronous' programming.
Since JavaScript is single threaded, your veryLongProcess() will in fact cause the alert to trigger after 1000ms because of something called blocking.
Be aware that blocking JavaScript can degrade the user experience significantly, such as locking up the browser, or causing it to show a 'kill script' dialog, breaking the functionality of your process.

What you're looking for is called "callback functions." You can pass functions as a variables to other functions, and then execute them whenever you want. I wrote a quick sample for how it works below (untested).
function longProcess(callback){
//a bunch of code execution goes here
var testNumber = 5;
//This portion of code happens after all desired code is run
if (callback != undefined){ //Check to see if a variable 'callback' was passed... we're assuming it's a function
callback(testNumber); //Execute the callback, passing it a value
}
}
function testCallback(number){
alert("Number: " + number); //Alert box will popup with "Number: 5"
}
longProcess(testCallback); //Call your long process, passing another function as a variable

Related

What happens if call two functions when button click event in javaScript

I'm tying to call two functions in JavaScript when a button click event happens.
<button type="submit" id="mySubmit" onClick="submitInput();getAll()">Search</button>
So I wondered what function will call first. And I have no idea.
Will the submitInput() executes first or getAll() or both executes at the same time concurrently. ?
It executes the same way as ordinary javascript. submitInput() executes first. I would not reccomend doing it this way though. It would be considered bad practice. keep your javascript out of your HTML ok.
Lastly, just because something executes first, does not mean that it will finish first.. javascript is both async and synchronous in some cases.
JavaScript is by nature mono-thread, that is to say its engine can only compute one operation at once (it is not parallel !). It means that as long as a process is not finished, the user remains stuck in front of his browser and has to wait till the end. Theoritically :)
Fortunately, JS is also asynchronous, it means that one is able to free the user thread, waiting for some other conditions to be fullfilled to continue the computation. To be more accurate, the execution of some functions can be delayed, one of the simplest examples is the use of the functions setTimeout() (once) or setInterval() (several times). A callback is a function triggered only under some conditions (i.e. a time interval expires, a script sends an answer, etc...). It prevents the browser from being "freezed", waiting for the result of a computation.
In your case, if there isn't any asynchronous call, the functions will be executed in the order you gave. Once the first is completed, the second will be triggered.
Try those two dummy functions :
function myFunction() {
for (var iter = 0; iter < 500000000; iter++) {
if (iter==499999999) {alert ("done !");}
}
}
function myFunction2() {
alert ("Hi there !");
}
Call them in this order, then change their order. The second will always be executed once the first is complete.

why is error in Javascript internal/external file stops the below code too?

The Error in JavaScript internal/external file also stops the below code
For example:
var myObj = {};
myObj.other.getName = function(){
console.log('other is not defined');
};
alert('this will not show');
in above code, the alert will not come as the above code has error.
I added the same code in one file tst1.js and below this add one more file tst2.js. put alert('in tst2.js') in it. the tst2 alert come while tst1 not. it is some what related to
code compilation/interpretation.
It's much appreciated If someone explain me this behavior :)
This is the default behaviour of JavaScript. Avoid errors and the code will run normally.
Also you can handle errors with try...catch: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
All JS implementations are, AFAIK, single threaded. This means that all of your code is executed sequentially, on a single thread (logically). If this thread encounters a fatal error, it grinds to a halt. All code that comes after the point where the error occurs is ignored (the JS engine halted, no work is done anymore).
To clarify: it does not matter how many files you have. All of the JS code is stringed together into one big script, and this one script is executed sequentially (execution point starts at line 1 of the first script, and ends at the last line of the last script). Any errors in that code will cause the overall execution to grind to a halt:
//file1.js
var foo = (function()
{
console.log('This file is flawless, but pointless');
}());
//file2.js
foo();//calls previously defined function, assigned to var foo
//file3.js
fudhfsiufhi;//ERROR
//file4.js
foo();//will never get executed, because an error occurred in file3.js
Remove file3, or indeed fix the error, and everything will work as expected.
Allthough JS code is executed/evaluated sequentially, event handlers, callbacks, intervals, and timeouts might lead you to believe otherwise. Couple that with the fact that you have some control over what code is executed when, but not full control, and you get situations that, at first, seem rather counter intuitive. Consider this:
setTimeout(function()
{
massive(syntaxError) -123 + "here";
},0);//zero MS
alert('This will show');
This oddity is well documented, but it has to do with JS having a callback/handler loop, and queue. The setTimeout sets a timeout, to call the anonymous function in 0ms (immediately), but that callback is sent to the queue, which is checked periodically. Before the queue is checked (and the callback invoked), the alert will show. That's why the interval you pass to setTimeout or setInterval is not guaranteed to be exactly N milliseconds.
You can postpone a call to a method somewhat, by adding a call to the queue, like in the snippet above. But when the queue is processed, and what order the queued calls will be performed in are things you have no real say in. No say whatsoever.
It doesn't matter how many files, or how many statements that come before or after the problematic piece of code: there is no thread left to carry on.
The code you posted has a pretty clear error in it: you're assigning a property to other (a property of myObj, but this property is not defined anywhere, let alone defined as an object. Fix it by declaring properties first, before accessing them:
var myObj = {other: {}};//other is an empty object literal
myObj.other.getName = function()
{
console.log('This works');
};
alert('And the alert will show');
Your current code evalutes to:
var myObj = {};//object
var (myObj.other).getName = ...;
//evaluates to undefined
undefined.getName = ...//ERROR
undefined is a primitive value, actually signifying the absence of a value. undefined, therefore, cannot be accessed as an object, it can't be assigned properties.
Note:
This is just for completeness' sake, but JS is indeed single-threaded most of the time, but ECMAScript5 introduced Worker's which allow for some restricted form of multi-threading (without shared state, for example). Read through the MDN documentation on workers if you want to know more.

Function only being executed with a delay of a keyup event

EDIT: I would like to have one function being called and executed after one second of the last keyup event.
Here's my code: http://jsfiddle.net/gKkAQ/
JS:
function aFunction() {
setTimeout(function () {
console.log("1");
}, 1000);
}
$(document).ready(function () {
$("#Input").keyup(function () {
aFunction();
});
});
HTML:
<input type="text" id="Input"></input>
You can easily run the JSFiddle and see in your console that no matter how fast you type, the function will be executed regardless of its previous execution status (in this case, setTimeout is not done yet in 1 second, but if you keep typing, ALL function calls will be executed)
"you will see the function being executed every second. I would like it to be executed after one second of the last keyup action"
The setTimeout() function returns an id that you can pass to clearTimeout() to prevent the timeout from occurring - assuming of course that you call clearTimeout() before the time is up.
var timeoutId;
function aFunction() {
clearTimeout(timeoutId);
timeoutId = setTimeout(function () {
console.log("1");
}, 1000);
}
$(document).ready(function () {
$("#Input").keyup(function () {
aFunction();
});
});
There is no harm in calling clearTimeout() with the id of a timeout that did already happen, in that case it has no effect.
So the above code clears the previous timeout (if there is one) and then creates a new one, with the effect that the anonymous function with the console.log() will only be execute 1000ms after the user stops typing. If the user starts typing again after waiting more than 1000ms that will queue up another timeout.
NOTE: THIS ANSWER CORRESPONDS TO THE INITIAL, VERY GENERAL QUESTION, BEFORE IT WAS SUBJECT TO EXTENSIVE EDITING AND TRANSFORMED IN A VERY SPECIFIC ONE.
It depends on your exact execution environment. Theoretically, JavaScript is single-threaded. The situation you describe should never happen. In practice, however, it does happen (especially inside browsers), and there is no way to fully control it.
The closest alternative to "control" is to start by checking the value of a global "activation counter" variable. If it is 0, immediately increment it and proceed with execution. Decrement it when exiting.
Why this doesn't work? Because 2 activations can reach the test at the same time. As the variable is 0, both tests will succeed and both will procceed to increment the variable and execute. As with most syncronization/concurrency issues, problems will not occurr systematically, but randomly every now and then. This makes things difficult to detect, reproduce and correct.
You can try to ask two times for the variable, as in:
if( activationCounter <= 0 ) {
if( activationCounter <= 0 ) {
activationCounter++;
// Execution
activationCounter--;
}
}
In many circles this has been described as a solution to the problem, but it only reduces the probability of conflict (by quite a bit, but not to zero). It's just the result of a bad understanding of the "double-checked locking" pattern. Problems will still occur, but with much less frequency. I'm not sure if this is good or bad, as they will be even more difficult to detect, reproduce and correct.

Can I use setTimeout to create a cheap infinite loop?

var recurse = function(steps, data, delay) {
if(steps == 0) {
console.log(data.length)
} else {
setTimeout(function(){
recurse(steps - 1, data, delay);
}, delay);
}
};
var myData = "abc";
recurse(8000, myData, 1);
What troubles me with this code is that I'm passing a string on 8000 times. Does this result in any kind of memory problem?
Also, If I run this code with node.js, it prints immediately, which is not what I would expect.
If you're worried about the string being copied 8,000 times, don't be, there's only one copy of the string; what gets passed around is a reference.
The bigger question is whether the object created when you call a function (called the "variable binding object" of the "execution context") is retained, because you're creating a closure, and which has a reference to the variable object for the context and thus keeps it in memory as long as the closure is still referenced somewhere.
And the answer is: Yes, but only until the timer fires, because once it does nothing is referencing the closure anymore and so the garbage collector can reclaim them both. So you won't have 8,000 of them outstanding, just one or two. Of course, when and how the GC runs is up to the implementation.
Curiously, just earlier today we had another question on a very similar topic; see my answer there as well.
It prints immediately because the program executes "immediately". On my Intel i5 machine, the whole operation takes 0.07s, according to time node test.js.
For the memory problems, and wether this is a "cheap infinite loop", you'll just have to experiment and measure.
If you want to create an asynchronous loop in node, you could use process.nextTick. It will be faster than setTimeout(func, 1).
In general Javascript does not support tail call optimization, so writing recursive code normally runs the risk of causing a stack overflow. If you use setTimeout like this, it effectively resets the call stack, so stack overflow is no longer a problem.
Performance will be the problem though, as each call to setTimeout generally takes a fair bit of time (around 10 ms), even if you set delay to 0.
The '1' is 1 millisecond. It might as well be a for loop. 1 second is 1000. I recently wrote something similar checking on the progress of a batch of processes on the back end and set a delay of 500. Older browsers wouldn't see any real difference between 1 and about 15ms if I remember correctly. I think V8 might actually process faster than that.
I don't think garbage collection will be happening to any of the functions until the last iteration is complete but these newer generations of JS JIT compilers are a lot smarter than the ones I know more about so it's possible they'll see that nothing is really going on after the timeout and pull those params from memory.
Regardless, even if memory is reserved for every instance of those parameters, it would take a lot more than 8000 iterations to cause a problem.
One way to safeguard against potential problems with more memory intensive parameters is if you pass in an object with the params you want. Then I believe the params will just be a reference to a set place in memory.
So something like:
var recurseParams ={ steps:8000, data:"abc", delay:100 } //outside of the function
//define the function
recurse(recurseParams);
//Then inside the function reference like this:
recurseParams.steps--

Javascript Anonymous Functions and Global Variables

I thought I would try and be clever and create a Wait function of my own (I realise there are other ways to do this). So I wrote:
var interval_id;
var countdowntimer = 0;
function Wait(wait_interval) {
countdowntimer = wait_interval;
interval_id = setInterval(function() {
--countdowntimer <=0 ? clearInterval(interval_id) : null;
}, 1000);
do {} while (countdowntimer >= 0);
}
// Wait a bit: 5 secs
Wait(5);
This all works, except for the infinite looping. Upon inspection, if I take the While loop out, the anonymous function is entered 5 times, as expected. So clearly the global variable countdowntimer is decremented.
However, if I check the value of countdowntimer, in the While loop, it never goes down. This is despite the fact that the anonymous function is being called whilst in the While loop!
Clearly, somehow, there are two values of countdowntimer floating around, but why?
EDIT
Ok, so I understand (now) that Javascript is single threaded. And that - sort of - answers my question. But, at which point in the processing of this single thread, does the so called asynchronous call using setInterval actually happen? Is it just between function calls? Surely not, what about functions that take a long time to execute?
There aren't two copies of the variable lying around. Javascript in web browsers is single threaded (unless you use the new web workers stuff). So the anonymous function never has the chance to run, because Wait is tying up the interpreter.
You can't use a busy-wait functions in browser-based Javascript; nothing else will ever happen (and they're a bad idea in most other environments, even where they're possible). You have to use callbacks instead. Here's a minimalist reworking of that:
var interval_id;
var countdowntimer = 0;
function Wait(wait_interval, callback) {
countdowntimer = wait_interval;
interval_id = setInterval(function() {
if (--countdowntimer <=0) {
clearInterval(interval_id);
interval_id = 0;
callback();
}
}, 1000);
}
// Wait a bit: 5 secs
Wait(5, function() {
alert("Done waiting");
});
// Any code here happens immediately, it doesn't wait for the callback
Edit Answering your follow-up:
But, at which point in the processing of this single thread, does the so called asynchronous call using setInterval actually happen? Is it just between function calls? Surely not, what about functions that take a long time to execute?
Pretty much, yeah — and so it's important that functions not be long-running. (Technically it's not even between function calls, in that if you have a function that calls three other functions, the interpreter can't do anything else while that (outer) function is running.) The interpreter essentially maintains a queue of functions it needs to execute. It starts starts by executing any global code (rather like a big function call). Then, when things happen (user input events, the time to call a callback scheduled via setTimeout is reached, etc.), the interpreter pushes the calls it needs to make onto the queue. It always processes the call at the front of the queue, and so things can stack up (like your setInterval calls, although setInterval is a bit special — it won't queue a subsequent callback if a previous one is still sitting in the queue waiting to be processed). So think in terms of when your code gets control and when it releases control (e.g., by returning). The interpreter can only do other things after you release control and before it gives it back to you again. And again, on some browsers (IE, for instance), that same thread is also used for painting the UI and such, so DOM insertions (for instance) won't show up until you release control back to the browser so it can get on with doing its painting.
When Javascript in web browsers, you really need to take an event-driven approach to designing and coding your solutions. The classic example is prompting the user for information. In a non-event-driven world, you could do this:
// Non-functional non-event-driven pseudo-example
askTheQuestion();
answer = readTheAnswer(); // Script pauses here
doSomethingWithAnswer(answer); // This doesn't happen until we have an answer
doSomethingElse();
That doesn't work in an event-driven world. Instead, you do this:
askTheQuestion();
setCallbackForQuestionAnsweredEvent(doSomethingWithAnswer);
// If we had code here, it would happen *immediately*,
// it wouldn't wait for the answer
So for instance, askTheQuestion might overlay a div on the page with fields prompting the user for various pieces of information with an "OK" button for them to click when they're done. setCallbackForQuestionAnswered would really be hooking the click event on the "OK" button. doSomethingWithAnswer would collect the information from the fields, remove or hide the div, and do something with the info.
Most Javascript implementation are single threaded, so when it is executing the while loop, it doesn't let anything else execute, so the interval never runs while the while is running, thus making an infinite loop.
There are many similar attempts to create a sleep/wait/pause function in javascript, but since most implementations are single threaded, it simply doesn't let you do anything else while sleeping(!).
The alternative way to make a delay is to write timeouts. They can postpone an execution of a chunk of code, but you have to break it in many functions. You can always inline functions so it makes it easier to follow (and to share variables within the same execution context).
There are also some libraries that adds some syntatic suggar to javascript making this more readable.
EDIT:
There's an excelent blog post by John Resig himself about How javascript timers work. He pretty much explains it in details. Hope it helps.
Actually, its pretty much guaranteed that the interval function will never run while the loop does as javascript is single-threaded.
There is a reason why no-one has made Wait before (and so many have tried); it simply cannot be done.
You will have to resort to braking up your function into bits and schedule these using setTimeout or setInterval.
//first part
...
setTimeout(function(){
//next part
}, 5000/*ms*/);
Depending on your needs this could (should) be implemented as a state machine.
Instead of using a global countdowntimer variable, why not just change the millisecond attribute on setInterval instead? Something like:
var waitId;
function Wait(waitSeconds)
{
waitId= setInterval(function(){clearInterval(waitId);}, waitSeconds * 1000);
}

Categories