Skip to content

Instantly share code, notes, and snippets.

@timkg
timkg / gist:5568259
Last active December 17, 2015 06:49
A simple implementation of Interfaces in Javascript. Allows you to define Interfaces with a bunch of methods. Defines Function.prototype.implement to be called on constructor functions which want to implement an interface. Throws errors if not all interface methods were declared.
function Interface(methodNames) {
var self = this;
methodNames.forEach(function(name) {
self[name] = function() {
throw new Error('Interface methods should not be called directly. Overwrite with specific implementation details.');
};
});
}
Function.prototype.implement = function(_interface, methodHash) {
@timkg
timkg / gist:4048408
Created November 9, 2012 21:34
Slightly altered code from page 3 of Async Javascript
var clickCount = 0, link;
link = document.getElementById('masochist')
link.innerHTML = 'How many times can you click me?';
link.onclick = function(){
clickCount++;
link.onclick = function(){ clickCount++; };
start = new Date();
while (new Date() - start < 5000) {}
console.log(clickCount); // this will always be 1
@timkg
timkg / gist:4048050
Created November 9, 2012 20:32
Code from page 3 of the book Async Javascript
var clickCount = 0, link;
link = document.getElementById('masochist')
link.innerHTML = 'How many times can you click me?';
link.onclick = function(){
clickCount++;
link.onclick = function(){ clickCount++; };
start = new Date();
while (new Date() - start < 5000) {}
console.log(clickCount); // this will always be 1
@timkg
timkg / gist:4040283
Created November 8, 2012 17:37
Async function calls (like timer or event callbacks) are not executed from the current call stack, but pushed to the end of the queue, creating their own new call stack.
function stuff() {
var start = new Date();
// notice how 'stuff' is in the the call stack
debugger;
setTimeout(function timeout() {
var end = new Date()
, diff = end - start;
// notice how 'stuff' is NOT in the call stack
debugger;
console.log( diff + 'ms have passed' );
function Paper() {
}
Paper.prototype.beats = function( o ) {
return o.beatenByPaper();
};
Paper.prototype.beatenByPaper = function() {
return false;
};
function Paper() {};
Paper.prototype.beats = function( o ) {
if( o.constructor === Rock ) {
return true;
} else if ( o.constructor === Paper ) {
return false;
} else if ( o.constructor === Scissors ) {
return false;