Skip to content

Instantly share code, notes, and snippets.

pattern to replace setInterval with setTimeout

Register a task with setInterval and a interval is not desirable, since the task can take more time than the interval, so the compiler will skip through the current cycle. Replace setInterval with setTimeout with following pattern:

setInterval(function() {
    runSomething();
}, interval);

with

(function loop() {

Why passing undefined to Immediately invoking function

(function(window, document, undefined) {...})(window, document);
  • save undefined variable from redeclearation
  • save bit from minification, since the variables will be replaced with shorter alias.
set nocompatible
filetype on
filetype indent on
filetype plugin on
syntax enable
set ignorecase
set hlsearch

Object Descriptor takeaways

A descriptor is an object which describe how the property behaves.

use object literal

Simplest way to define an object is by using object literal, by doing so, the created object are set with implicit descriptors to all "true". As illustrated below:

var objectLiteral = {
    name: 'foo'
};
"hello".missing; // log undefined
[][99]; // log undefined
{} + {}; // log NaN
[] + []; // log "" (empty string)
[] + {}; // log "[object Object]"
{} + []; // log 0
@geastwood
geastwood / ns.js
Last active December 24, 2015 21:09
simple namespace function
// simple namespace function
// use: var newNs = namespace('this.is.a.new.namespace');
var namespace = function(namespace, context) {
if (!namespace) { throw 'namespace string is required' };
var ns = namespace.split('.');
var current = context || this;
@geastwood
geastwood / singleton.js
Created October 4, 2013 21:55
js singleton template
window.singleton = (function(){
var instance;
var init = function() {
return Math.random();
};
return {
@geastwood
geastwood / isArray.js
Last active December 24, 2015 15:59
isArray, determine array by Object toString property
// use Object toString method to determine Array
var isArray = function(obj){
return Object.prototype.toString.call(obj) === '[object Array]';
}