Tuesday, September 11, 2012

Recursive setTimeout pattern

The Recursive setTimeout pattern is most commonly used when we want periodically running a piece of functionality, related to duration (most commonly used to query a data source).

This may sounds like what setInterval does, but there is a problem with using setInterval. Because JavaScript is asynchronous, setInterval method actually does not wait for the previous function to finish it's execution before begins the next time period. What if the function was waiting for an AJAX response? Function execution can get out of order.

So, the idea is to use setTimeout. setTimeout can ensure order of execution:

Monday, September 10, 2012

Asynchronous execution pattern

Before we go thought this pattern, lets cover some basic notes about JavaScript timers:

1. There two kinds of timers in JavaScript:
  • setTimeout
  • setInterval
2. Both take two arguments, a function to invoke and a delay period
3. setTimeout will execute the function once
4. setInterval will execute continuously with the specified delay between each execution
5. Delays < 4ms will be bumped to 4ms
6. Important: Timers wont start until the outer most function is finished

Browsers are typically single threaded, they either update the UI or executing JavaScript. Long running JavaScript blocks the UI and browser is unresponsive.

Splitting long-running code over setTimeout blocks releases the thread:

  • While processing a loop limit the scope to a small time window
  • Ensure that there is enough of a gap between timeouts restarting

So let's see a basic example:



So, this is very trivial example, but it's very common scenario in web applications when we gather data through ajax. The problem which can arise is that we don't know how long the process will take, or on low power devices such as mobiles or tablets processing this array could take a lot longer than we would like and UI can stop responding.

One way we can get around this is to create a function which will allow us to defer the execution on multiple periods of time:

Observable properties pattern

If you’re familiar with C#, think about the INotifyPropertyChanging and INotifyPropertyChanged interface to implement observable properties.

Here are some points before we implement observable properties in JavaScript:

- Properties  implemented as methods
- Check the incoming value and decide if you want to update
- Return private variable
- Store event handlers in an array
- Utilise return values to abort the updating process

Here is the implementation:


Note: With ECMAScript5 properties can have methods body (similar to how .NET properties look) and it's very powerful, but be careful because this option is available in current generation browsers.

Here is an example:

Chaining pattern

Method chaining is a common technique for invoking multiple method calls in object-oriented programming languages. Each method returns an object (possibly the current object itself), allowing the calls to be chained together in a single statement (Wikipedia definition). This technique was made popular in several libraries, like jQuery.

Let's see JQuery example of method chaining:

Here is how we can implement method chaining in JavaScript (Calculator example):

Function argument patterns

UPDATE:  ECMAScript 6 introduces rest parameters to help us with this and other pitfalls. Rest parameters are indicated by three dots … preceding a parameter. Named parameter becomes an array which contains the rest of the parameters. Please check official MDN documentation here.

ORIGINAL POST
Let's create a simple JavaScript function that takes 3 arguments to it. Inside the function, we made operation against this arguments. We add each one together and then we return resulting value. Then we execute these function three times. The first time we pass three arguments, and we expect a result of 6. But, in the second example we passing 4 arguments instead of 3 arguments, and in the final example, we pass 2 arguments instead of 3 arguments which are expected from the function. 



So, how we expect JavaScript to deal with these? 

Unlike more traditional programming languages like C# and VB, arguments in javascript are more dynamic. All variables in JavaScript arguments are untyped, and unspecified arguments become undefined. 

So in our example when we call our function with 2 arguments, the 3th argument will become undefined. So, we got output of NaN. In our second call to the function where we pass 4 arguments, we didn't get error because JavaScript ignores 4th argument.

But, sometimes you might want to access this arguments if there are specified. JavaScript provides very easy way to do this through an arguments object which exists inside every function. The arguments object is very special object in JavaScript. It's kind of like an array, but it's not array. You can access all arguments through numeral indexes. The arguments object has lenght property so you can iterate through, as an array. But it's not actually array, because you can not sortring, filtering...

That means than we can implement some intresting things, such as next code example:



Here we take the same concept, but instead of passing the arguments, we just accessing arguments object. This concept is also used quite commonly in a lot of JavaScript libraries like JQuery, where you can pass in various different number of arguments types, like string, function, dom object and JQuery will allow to operate against this.