Skip to content

Instantly share code, notes, and snippets.

@iamjpg
Created October 20, 2011 20:30
Show Gist options
  • Save iamjpg/1302277 to your computer and use it in GitHub Desktop.
Save iamjpg/1302277 to your computer and use it in GitHub Desktop.
Javascript Riddle
<!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