Timed Loop

node v8.17.0
version: master
endpointsharetweet
This is a playground to test JavaScript. It runs a completely standard copy of Node.js on a virtual server created just for you. Every one of npm’s 300,000+ packages are pre-installed, so try it out:
/* // First Try, FAIL: Prints `1 2 3 4 5` all at once, after 2 seconds for (let i = 1; i <= 5; i++) { setTimeout( () => { console.log(i) }, 2000); // All iterations are logged to console at +2000ms } */
/* // Second Try, FAIL: Prints `6 6 6 6 6` one after the other, every 2 seconds for (var i = 1; i <= 5; i++) { // Traditional `var` setTimeout(function() { console.log(i); }, 2000 * i); // Traditional function } */
/* // Third Try, SUCCESS: Prints `1 2 3 4 5` one after the other, every 2 seconds // Closure for (var i = 1; i <= 5; i++) { // Traditional `var` (function(x) { setTimeout(function() { console.log(x); }, 2000 * x); // Traditional function })(i); } */
/* // Fourth Try, SUCCESS // ES6 `let` for (let i = 1; i <= 5; i++) { // ES6 `let` setTimeout(function() { console.log(i); }, 2000 * i); // Traditional function } */ /* // Variation: with arrow function for (let i = 1; i <= 5; i++) { // ES6 `let` setTimeout(() => { console.log(i); }, 2000 * i); // ES6 arrow function } */
/* // Fifth Try, FAIL: Prints `1 2 3 4 5` all at once // Recursion var i = 1; (function CountToFive() { setTimeout(function () { while (i <= 5) { // Using `while` breaks the code console.log(i); i++; } CountToFive(); }, 2000); })(); */
/* // Sixth Try, SUCCESS // Recursion var i = 1; (function CountToFive() { setTimeout(function () { if (i <= 5) { // Using `if` makes it work console.log(i); i++; } CountToFive(); }, 2000); })(); */
/* // Seventh Try, SUCCESS // Verbose: with two extra function calls within `setTimeOut()` (function CountToFive() { for (let i = 1; i <= 5; i++) { setTimeout(function(x) { return function() { console.log(x); }; }(i), 2000 * i); } })(); */
// Eighth try, SUCCESS // Recursion With Stop var i = 1; (function CountToFive() { let timer = setTimeout(function () { if (i <= 5) { // Using `if` makes it work console.log(i); i++; } else { clearTimeout(timer); // Stops timer if `i` reaches 5 } CountToFive(); }, 2000); })(i);
Loading…

no comments

    sign in to comment