Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Polyfill array object in order to enable the loop in steps
<html>
<body>
<span id='counter' style='position:fixed;bottom:10px;right:10px;color:white;background:black;padding:10px;'></span>
</body>
<script>
Object.defineProperty(Array.prototype,'onPassLast',{
get: function(){this.onPassLastFN(this)},
set: function(fn){this.onPassLastFN=fn;}
});
Object.defineProperty(Array.prototype,'loop',{
set: function(cb){
if(typeof cb == "function"){this.callBack=cb;}else{this.currentIndex=this.currentIndex+cb;};
this.currentIndex=this.currentIndex==undefined?0:this.currentIndex;
if(this.currentIndex>=this.length){
return this.onPassLast;
}else{
this.callBack!=undefined?this.callBack(this[this.currentIndex],this):false;
};
}
});
Object.defineProperty(Array.prototype,'next',{
get: function(){this.loop=1;}
});
var ajax=function(url,cb){//a trivial version of Ajax, only for download data from a remote server
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
cb(JSON.parse(xhttp.responseText));
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
var counter=document.getElementById("counter");
ajax("http://jsonplaceholder.typicode.com/photos",function(data){
data=data.slice(0, 50);//what the heck, I just need 50 elements :)
data.onPassLast=function(array){alert("finish!", JSON.stringify(array));}//on passed all elements, do this function
data.loop=function(element,array){
var img=document.createElement("img");
img.src=element.url;
img.style.width="100px";
img.onload=function(){
window.scrollTo(0,document.body.scrollHeight);//subtle touch
array.next;//and when the image is loaded move to next member of the series
counter.innerHTML=data.currentIndex+"/"+data.length;//Show me on counter
}
document.body.appendChild(img);
}
});
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment