In this post we will talk about timers and their usage in JavaScript

Timers are available in the Window object. It takes two parameters the time in milliseconds and expression or the function. We have 2 types of timers:

setInterval (func, milliseconds) – this timer is recursive and will evaluate the expression each time when the timespan that we have specified occurs.

setTimeout (func, milliseconds) – this timer is executes the expression once when the timespan we specified is passed.

We also have clear method available on both types of timers.

clearInterval (id) – takes the id of the timer to clear so that the specified code is not executed at specified intervals.

clearTimeout (id) – takes the id of the timer to clear so that the specified code is not executed at specified timeout time.

Another thing to keep in mind about the timers is that the timers run on the same thread as the UI events. All JavaScript in the browser executes in the single thread asynchronous events and this forces JavaScript asynchronous events to queue waiting for execution. So whenever we specify time for a timer we can be sure that it will not fire before the specified time. Generally the delays are unnoticeable by the end users.

Timeout

This type of timers are useful at places where we want to execute a block of code after a specified amount of time or at some timeout.

Recurring function call

This timer is useful when we want to call a function for multiple times at some specified interval. May be useful when we are performing some time based actions or animations.

Clear Interval

This function clears the Interval timer and it will not execute any further.

 

Instead of passing a global function we can also pass an anonymous function in the setInterval timer.

The code for this post can be found here.

Any questions, comments or feedback is most welcome.

Hi guys,

In this post we will walk through the Date object that is available in JavaScript and the various capabilities of that object and various ways can use it in our application

Date in JavaScript is powerful enough to suffice for most of the requirements we have in our applications. Interesting thing to note here is that numeric value of date is the number of milliseconds that have lapsed after 01Jan1970 UTC (all the leap time is ignored).

Another interesting thing that we can do with date in JavaScript is create a future date by adding days, hours, months, etc.

The various methods available on Date are:

getDate() Returns the day of the month (from 1-31)
getDay() Returns the day of the week (from 0-6)
getFullYear() Returns the year (four digits)
getHours() Returns the hour (from 0-23)
getMilliseconds() Returns the milliseconds (from 0-999)
getMinutes() Returns the minutes (from 0-59)
getMonth() Returns the month (from 0-11)
getSeconds() Returns the seconds (from 0-59)
getTime() Returns the number of milliseconds since midnight Jan 1, 1970
getTimezoneOffset() Returns the time difference between UTC time and local time, in minutes
getUTCDate() Returns the day of the month, according to universal time (from 1-31)
getUTCDay() Returns the day of the week, according to universal time (from 0-6)
getUTCFullYear() Returns the year, according to universal time (four digits)
getUTCHours() Returns the hour, according to universal time (from 0-23)
getUTCMilliseconds() Returns the milliseconds, according to universal time (from 0-999)
getUTCMinutes() Returns the minutes, according to universal time (from 0-59)
getUTCMonth() Returns the month, according to universal time (from 0-11)
getUTCSeconds() Returns the seconds, according to universal time (from 0-59)
getYear() Deprecated. Use the getFullYear() method instead
parse() Parses a date string and returns the number of milliseconds since midnight of January 1, 1970
setDate() Sets the day of the month of a date object
setFullYear() Sets the year (four digits) of a date object
setHours() Sets the hour of a date object
setMilliseconds() Sets the milliseconds of a date object
setMinutes() Set the minutes of a date object
setMonth() Sets the month of a date object
setSeconds() Sets the seconds of a date object
setTime() Sets a date and time by adding or subtracting a specified number of milliseconds to/from midnight January 1, 1970
setUTCDate() Sets the day of the month of a date object, according to universal time
setUTCFullYear() Sets the year of a date object, according to universal time (four digits)
setUTCHours() Sets the hour of a date object, according to universal time
setUTCMilliseconds() Sets the milliseconds of a date object, according to universal time
setUTCMinutes() Set the minutes of a date object, according to universal time
setUTCMonth() Sets the month of a date object, according to universal time
setUTCSeconds() Set the seconds of a date object, according to universal time
setYear() Deprecated. Use the setFullYear() method instead
toDateString( Converts the date portion of a Date object into a readable string
toGMTString() Deprecated. Use the toUTCString() method instead
toISOString() Returns the date as a string, using the ISO standard
toJSON() Returns the date as a string, formatted as a JSON date
toLocaleDateString() Returns the date portion of a Date object as a string, using locale conventions
toLocaleTimeString() Returns the time portion of a Date object as a string, using locale conventions
toLocaleString() Converts a Date object to a string, using locale conventions
toString() Converts a Date object to a string
toTimeString() Converts the time portion of a Date object to a string
toUTCString() Converts a Date object to a string, according to universal time
UTC() Returns the number of milliseconds in a date string since midnight of January 1, 1970, according to universal time
valueOf() Returns the primitive value of a Date object

Source – http://www.w3schools.com/jsref/jsref_obj_date.asp

Accessing the current date and parts of the date

We can create a Date object in Javascript that returns the current date time in current time zone. This happens when we do not pass any parameters while passing the Date object.

We pass different types of parameters to create the date we are looking for. We can pass

Number of milliseconds that have lapsed after 01 Jan 1970 00:00:00:000 UTC –> will return the date adding the lapsed milliseconds to base date of 01 Jan 1970 00:00:00:000 UTC.

String that is parseable into date –> will return the date that is parsed from the string.

Year, Month, Day, Hours, Minutes, Seconds, Milliseconds –> A date will be created if we pass just the Year, Month and Day. The remaining parameters will be considered as 0.

We can use the methods that return the individual part of the date.

Accessing dates in UTC timezone

We also have methods which return the UTC equivalent of the date. So whatever operations that we have done till now on the local date we can perform all of them to get the UTC time and date.

Get CurrentTime

It returns the number of milliseconds that have lapsed since 01 Jan 1970 00:00:00:000 UTC

Converting Date To and From ISO 8601 format

Convert Date in ISO 8601 Format

There is a method (toISOString) available on the Date object. It returns the date in ISO format which looks something like below:

2013-07-29T18:56:20.370Z

This format separates the date and time by placing T in between them. Also if this string is in UTC timezone it is suffixed by Z and if it is not in the UTC timezone then it tells the time difference between the current timezone and UTC timezone by +hh:mm or –hh:mm.

Convert ISO 8601 date into standard format accepted by Date method

If we are using older versions of the browser and we try to use the string date returned by the toISOString as a parameter to create a date then we will get an invalid date error. So before we pass this string to create a date we need to convert it into a format acceptable by the Date object. So could use the function below that will convert the ISO 8601 string into format acceptable by the date object.

However if we are running the latest browsers we could simply pass the ISO 8601 formatted string as a parameter to the date object and we will get the localized date.

Create future date

We can do that by either passing the individual parts of the date or use the set method available to set the values of the individual parts of the date.

Find time elapsed

There are times when we need to know how long a function takes to execute. So do that all we need to do is create a Date object before we call the function and then we create another object when the control returns back from the function and then we subtract both the times.

When we apply mathematical operations on date apart from subtraction we get different results.

Date + Date = string concatenation of date

Date – Date = Difference of milliseconds equivalent of date

Date / Date = Division of milliseconds equivalent of the date

Date * Date = Multiplication of milliseconds equivalent of date

The code for this post is available here.

Any comments, feedback or questions are most welcome!!

In this post i am going to talk about the capabilities available in JavaScript for strings.

 

Strings

Strings are bunch of characters or spaces grouped together. Strings can be represented placing these characters inside single quotes (‘ ’) or double quotes (“ ”). Inside these single and double quotes we could use zero or more characters.

  • Strings are the most used datatype in Javascript.
  • They are used within the client side JavaScript code.
  • When making an ajax call to the server.
  • Serializing the JavaScript objects passed over the wire.
  • The ToString method is available on the JavaScript objects and it returns the string representation of the object in serialized format.
  • One of the JavaScript primitive types (number, Boolean, null and undefined). It can be an object as well.
  • Strings are JavaScript literal format for number, Boolean, arrays, objects and regex.

Note – A literal is a notation for representing fixed value in the source code.

  • Represented by single quotes (‘I am a String’) or double quotes (“I am a String”).
  • If we want to include quotes (‘, ’, “, ”), slashes (/, ), backspace (b), formfeed (f), newline (n), carriage return (I) or tab (t)  inside our string then we need to follow those quotes via backslash (). All charades in JavaScript are 16-bits wide.
  • There is no character type in JavaScript so we need to use string with one character.
  • The length property of string can be used to find out the number of characters in the string.
  • Strings are immutable. This means that once created they cannot be modified, so whenever we modify a string a new string is created with a new value.
  • Two strings are same if they have same characters in the same order.
  • We can convert a number to a string by using the .ToString() method.

Strings are value type

Strings are a value type in JS, so they can’t have any properties attached to them, no prototype, etc. Any attempt to access a property on them is technically performing the JS [[ToObject]] conversion (in essence new String).

function stringLiteral() {

a = “foo”

a.b = “bar”

alert(“a.b = ” + a.b); //Undefined

}

 

function stringObject() {

A = new String(“foo”);

A.b = “bar”;

alert(“A.b = ” + A.b); // bar

}

 

function compareLiteralToObject() {

alert(“Are ‘foo’ and new String(‘foo’) equal = ” + (“foo” === new  String(“foo”))); //fail bcoz string type if not equal to object type.

}

String Methods

tolowerCase –> Converts the string to lower case.

function lowerCaseString() {

alert(“Lower case string for ‘Foo’ is ” + “FOO”.toLowerCase()); //foo

}

concat –> Concats the string/s passed as the parameter.

It is equivalent to using + or += except that it is easier when passing multiple strings to concat.

function stringConcatination() {

var str = “foo “;

console.log(str.concat(“is “, “not “, “bar.”)); // foo is not bar.

 

str = “foo “;

 

console.log(str + “bar.”); // foo bar.

 

str = “foo “;

 

console.log(str += “bar.”);

}

Using this method we can not only concatenate string values but we also concatenate other data types to string.

localeCompare à Returns a number (-1, 0 or 1) indicating whether a reference string comes before or after or is the same as the given string in sort order.

function stringLocaleCompare() {

console.log(“foo”.localeCompare(“bar”)); //1

console.log(“bar”.localeCompare(“foo”)); //-1

console.log(“foo”.localeCompare(“foo”)); //0

}

String comparison can also be done by using operators like

== –> equal

!= –> not equal

=== –> strict equal

!== –> strict not equal

> –> greater than

>= –> greater than or equal

< –> less than

<= –> less than or equal

indexOf –> Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.

lastIndexOf –> Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.

function indexOfSubstring() {

console.log(“The position of 1st ‘foo’ in the string is ” + “foo is the same as bar but foo is the same as foo”.indexOf(‘foo’)); //The position of 1st ‘foo’ in the string is 0

 

console.log(“The position of last ‘foo’ in the string is ” + “foo is the same as bar but foo is the same as foo”.lastIndexOf(‘foo’)); //The position of last ‘foo’ in the string is 46

}

In both these methods we can also pass the index from where we want to start the search.

substr –> Returns the characters in a string beginning at the specified location through the specified number of characters.

substring –> Returns the characters in a string between two indexes into the string.

function substringFunc() {

console.log(“eat, sleep and code!!”.substring(15, 4)); // returns characters between the two specified indices

//  sleep and

console.log(“eat, sleep and code!!”.substr(15, 4)); // returns the characters starting at the specified index and till the number of characters specified

// code

}

valueOf –> Returns the primitive value of the specified object. It overrides the Object.prototype.valueOf method.

Note – This valueOf method is available on all JavaScript objects.

function valueOfObjects() {

var boolObj = true;

 

var numberObj = 4;

 

person = new Object();

person.firstname = “John”;

person.lastname = “Doe”;

person.age = 25;

person.eyecolor = “blue”;

var stringObj = “This is a string.”

 

console.log(boolObj.valueOf()); // true

console.log(numberObj.valueOf()); // 4

console.log(person.valueOf()); // Object {firstname: “John”, lastname: “Doe”, age: 25, eyecolor: “blue”}

console.log(stringObj.valueOf()); // This is a string.

}

split –> Splits a String object into an array of strings by separating the string into substrings.

function splitString() {

console.log(“eat,sleep,code”.split()); // [“eat,sleep,code”]

console.log(“eat,sleep,code”.split(‘,’)); // [“eat”, “sleep”, “code”]

console.log(“eat,sleep,code”.split(‘,’, 2));  // [“eat”, “sleep”]

// Regex split

console.log(“eat,sleep,code”.split(/e/)); //[“”, “at,sl”, “”, “p,cod”, “”]

}

Requires JavaScript 1.8.1

trim –> Trims whitespace from the beginning and end of the string. Part of the ECMAScript 5 standard.

Requires JavaScript 1.8.1 Non-standard

trimLeft –> Trims whitespace from the left side of the string.

trimRight –> Trims whitespace from the right side of the string.

function trimString() {

console.log(”       lsdjkflk        “); //        lsdjkflk

console.log(”       lsdjkflk        “.trim()); // lsdjkflk

console.log(”       lsdjkflk        “.trimLeft()); // lsdjkflk

console.log(”       lsdjkflk        “.trimRight()); //        lsdjkflk

}

If we are running the version of JavaScript below the specified version then we need to write our own trim method. It could look something like below.

function trimming(str) {

return str.replace(/(^\s*)|(\s*$)/g, “”);

}

function trimString() {

console.log(trimming(”       lsdjkflk        “)); // lsdjkflk

}

Other String methods

Source – https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

charAt –> Returns the character at the specified index.

charCodeAt –> Returns a number indicating the Unicode value of the character at the given index.

contains –>Determines whether one string may be found within another string.

endsWith –> Determines whether a string ends with the characters of another string.

match –> Used to match a regular expression against a string.

quote –> (Non-standard) Wraps the string in double quotes (“””).

replace –> Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.

search –> Executes the search for a match between a regular expression and a specified string.

slice –> Extracts a section of a string and returns a new string.

startsWith –> Determines whether a string begins with the characters of another string.

toLocaleLowerCase –> The characters within a string are converted to lower case while respecting the current locale. For most languages, this will return the same as toLowerCase.

toLocaleUpperCase –> The characters within a string are converted to upper case while respecting the current locale. For most languages, this will return the same as toUpperCase.

toLowerCase –> Returns the calling string value converted to lower case.

toSource –> (Non-standard) Returns an object literal representing the specified object; you can use this value to create a new object. Overrides the Object.prototype.toSource method.

toString –> Returns a string representing the specified object. Overrides the Object.prototype.toString method.

toUpperCase –> Returns the calling string value converted to uppercase.

Bonus – Including special characters in the strings

To include special characters in the string we need to include the Unicode hexadecimal format of the characters. I have added a few below. To include these characters need to be prefixed by \ (escape sequence).

function specialCharacters() {

console.log(“This page \u00A9 and \u00AE to Abhishek Shukla \u263A “); // This page © and ® to Abhishek Shukla ☺

}

A detailed list of the hexadecimal code can be found here.

Bonus – Prompt for user input

 

This is useful when want to get some user input only at some event or condition and do not want to add a text input control.

function promptForUserInput() {

var userInput = prompt(“What’s your name?”, “”);

 

console.log(“You entered – ” + userInput);

}

Some of these functions are live here. You can go ahead and play with them. All of these have been implemented by using knockout data binding

The source code for this post can be downloaded here.

Hi Guys,

 

In this post i am going to talk about how we could create an auto complete text box in HTML5 using DataList. Also we will see how we could use knockout to bind an observable array to the auto complete list. Then we will populate the data depending upon the selection of a user.

The first thing that we need to do is add a Scripts folder and then download the knockout.js into that folder. Then we will include the knockout.js script file into our html page.

[hr]

<html>
<head>
<title>HTML 5 Datalist Knockout Auto Complete Text Box</title>
</head>

<body>
<script type=”text/javascript” src=”Scripts/knockout-2.2.1.js” ></script>

</body>

</html>

[hr]

Now just below the script tag add another script tag. In this script tag we will define our view model with which we will bind our html view.

[hr]

<script type=”text/javascript” >
function userViewModel () {
this.users = ko.observableArray();
this.username = ko.observable(”);

this.users.push(“Abhishek Shukla”); this.users.push(“user 1”); this.users.push(“user 11”);
this.users.push(“user 2”); this.users.push(“user 22″);

this.currentUser = {
firstName: ko.observable(”),
lastName: ko.observable(”),
address: ko.observable(”)
};

this.setUser = function () {
if (this.username() !== ”) {
this.setCurrentUser(this.username());
}
}.bind(this);

this.setCurrentUser = function (username) {
var userFullName = username.split(‘ ‘);
this.currentUser.firstName(userFullName[0]);
this.currentUser.lastName(userFullName[1]);
this.currentUser.address(“Gurgaon, India”);
}.bind(this);
};
ko.applyBindings(new userViewModel());
</script>

[hr]

Now that our ViewModel is ready we will create a view and bind it to the ViewModel properties and events.

<p>Type User Name :
<input list=”Employees1″ data-bind=”value: username, onchange: setUser()” type=”text” />
<datalist id=”Employees1″ data-bind=”foreach: users”>
<option data-bind=”text: $data”></option>
</datalist>
</p>
<p>First Name : <span data-bind=”text: currentUser.firstName” /></p>
<p>Last Name : <span data-bind=”text: currentUser.lastName” /> </p>
<p>Address : <span data-bind=”text: currentUser.address” /> </p>

[hr]

Any questions, comments, feedback are most welcome.

The complete source code can downloaded from here.