Tuesday, January 7, 2014

Javascript code snippet

Here are some code snippets from
http://flippinawesome.org/2013/12/23/45-useful-javascript-tips-tricks-and-best-practices/


String.prototype.trim = function(){return this.replace(/^\s+|\s+$/g, "");};
Array.prototype.slice.call(arguments);
Object.prototype.toString.call(obj) === '[object Array]' ;
myArray.length = 0;

for (var name in object) { 
    if (object.hasOwnProperty(name)) {
        // do something with name                   
    } 
}

function escapeHTML(text) { 
    var replacements= {"<": "&lt;", ">": "&gt;","&": "&amp;", "\"": "&quot;"};                     
    return text.replace(/[<>&"]/g, function(character) { 
        return replacements[character]; 
    });
}

var xhr = new XMLHttpRequest ();
xhr.onreadystatechange = function () { 
    if (this.readyState == 4) { 
        clearTimeout(timeout); 
        // do something with response data
    } 

var timeout = setTimeout( function () { 
    xhr.abort(); // call error callback 
}, 60*1000 /* timeout after a minute */ );
xhr.open('GET', url, true); 

xhr.send();


var timerID = 0;
function keepAlive() {
    var timeout = 15000; 
    if (webSocket.readyState == webSocket.OPEN) { 
        webSocket.send(''); 
    } 
    timerId = setTimeout(keepAlive, timeout); 

function cancelKeepAlive() { 
    if (timerId) { 
        cancelTimeout(timerId); 
    } 
}

No comments:

Post a Comment