Created
October 20, 2011 20:30
-
-
Save iamjpg/1302277 to your computer and use it in GitHub Desktop.
Javascript Riddle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> | |
<title>JS Riddle</title> | |
</head> | |
<body> | |
<h3>Print 0 to 100 to the browser without using a global variable in JS</h3> | |
<div id="print"></div> | |
<script> | |
var printToBrowser = function () { | |
// For loop, duh. | |
for (i = 0; i <= 100; i ++) { | |
// Self executing function! | |
(function(j) { | |
// intervals yo! | |
setTimeout(function() { | |
// Print to browser | |
document.getElementById('print').innerHTML += j + '<br />'; | |
}, (i * 1000)); // Multiply it's value by 1000ms to delay print. | |
})(i); // Pass i back to the closure as j! | |
} | |
} | |
// Onload execute printToBrowser(); | |
window.onload = function () { | |
printToBrowser(); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment