Using javascript, suppose I need to print 1 to 10 and after printing each numbers, I need a break of 2 seconds. How can I do that?
you can utilize the setTimeout function which takes in a function and a time (in ms) to delay that function's call. Be careful using this inside a for loop though because it may not work the way you think (re: closures. for more info: http://bonsaiden.github.com/JavaScript-Garden/#function.closures).
// Watch out for closures. function printAndWait(i, limit, delay) { //base case if (i > limit) return; (function(e) { setTimeout(function() { console.log(e); printAndWait(i+1, limit, delay); }, delay); })(i); } // print from 0 to 10, 2000ms delay between printAndWait(0,10,2000);
fixed link: http://bonsaiden.github.com/JavaScript-Garden/#function.closures
thanks!!!
hey
Join our real-time social learning platform and learn together with your friends!