Javascript

Blocking vs non-blocking

A blocking operation:


console.log('Hello ' + write('Dribbit', 1000));

function write(text, delay) {
    var start = new Date().getTime();
    while (new Date().getTime() - start < delay) {
        // Waiting...
    }
    return text;
}

console.log('End log');

Install MySQL on Node.js

Add mysql dependency in the package.json file in the root of your project. Example of a package.json file:


{
  "name": "Dribbit",
  "description": "My default description",
  "private": true,
  "dependencies": {
    "mysql": "~2.0.0"
  },
  "repository": {
    "type": "git",
    "url": "git@bitbucket.org:UserName/repo.git"
  }
}

After saving package.json, run

npm install 

Create an ajax call with jQuery


	  $.ajax({
		  type: "POST",
		  url: "http://192.168.0.205:3030",
		  data: { 
			  username: "Dribbit", 
			  score: 1590 
			}
		})
		.done(function( msg ) {
		    console.log( "Message returned from the server: " + msg );
		});

Create a Node.js webserver

To create a node webserver, the core http module needs to be included. To include an existing module you can use the require function.


var http = require("http");

http.createServer(function(request, response) {
    response.writeHead(200,{"Content-Type":"text/plain"});
    response.write("Luke, I am your server");
    response.end();
}).listen(8888);

See the difference with a node server using express

Create a simple countdown object


/**
 * Create and process a new Countdown object.
 * 
 * @param seconds
 *  Integer
 */
function Countdown(seconds) {
	
	$('#timer').html(seconds);
	
	var timer = window.setInterval(function() {
	  if (seconds === 0) {
        clearInterval(timer);
        return;
	  }
      seconds -= 1;
      $('#timer').html(seconds);
	}, 1000);
	
	this.stop = function() {
      clearInterval(timer);
	}
	
}

Create a simple timer object


/**
 * A Timer object.
 */
function Timer() {
	
	var time = 0;
	$('#timer').html(time);
	
	var timer = window.setInterval(function() {
      time += 1;
      $('#timer').html(time);
	}, 1000);
	
	this.stop = function() {
      clearInterval(timer);
      $('#timer').html(time);
	}
	
}

HTML5 Geolocation - Locate a user's position


// Does the browser support geolocation?
// @see http://www.w3schools.com/html/html5_geolocation.asp.
if(navigator.geolocation) {
	// When clicked on deny, error function is triggered.
	navigator.geolocation.getCurrentPosition(success,error);
} else {
	console.log('Browser doesn\'t support geolocation, default geolocation unsupported action.');
}

function success(pos) {
	console.log('User allows, location specific action.');
}
function error(error) {
	console.log('User denies, default geolocation supported action.');
}

Pages

Subscribe to RSS - Javascript