print number from 1 to 10 after every 2 seconds - javascript

i want to print number after every n number of seconds and based on few conditions i am changing the timer as well as i am stopping the print function. i have done like this --
var myfunc = {
value : 1,
running : false,
timer : 1000,
start : function(){
this.running = true;
clearInterval(this.timeout);
this.timeout = setTimeout(function() {
myfunc.execute(myfunc);
}, myfunc.timer);
},
execute : function(){
if(!this.running) return false;
console.log( 'Currently at -- ' + (this.value++) );
if (this.value > 5 ){
this.changetiming();
}
if (this.value > 10 ){
this.stop();
return;
}else{
this.start();
}
},
changetiming : function(){
this.timer = 3000;
},
stop : function(){
this.running = false;
clearTimeout(this.timeout);
}
};
myfunc.start();
Now i want to know what is wrong with following code --
for(var i = 0; i <= 10; i++){
print(i);
}
function print(i){
setTimeout(function(){
console.log(i)
},2000);
}

here is the right way and easy way to do this in ES6+:
const printNumbersForEvery2Sec = (n)=>{
for (let i = 1; i <= n; i++) {
setTimeout( () =>{
console.log(i)
}, i * 2000)
}
}
printNumbersForEvery2Sec(10);
by multiplying i , each setTimeout() to be delayed 2 to 20 seconds (2000 x 1, 2000 x 2…) respectively.

I'm pretty sure the question "Why does this JavaScript code
for (var i = 0; i <= 10; i++){
print(i);
}
function print(i) {
setTimeout(function(){
console.log(i)
},2000);
}
print out the values 1 through 10 at once, after 2 seconds have elapsed?" has been asked before.
It is a common mistake.
What you are doing is calling print 10 times. Each call to print takes only a few microseconds. Why? Because it just calls setTimeout. Executing setTimeout takes only a few microseconds to complete. All the call does is schedule something to take place in the future. So within a few microseconds you have scheduled 10 things to take place at about 2 seconds in the future. All the schedulings happen at about the same time. So all the console logs take place at about the same time, two seconds after you scheduled them.
See Satapal's comment to your question for a nice way to do what you want to do.

#easiestway
for (var i = 0; i <= 10; i++){
print(i);
}
function print(i) {
setTimeout(function(){
console.log(i)
},i*2000);
}

Using IIFE, Clouser, and Global Scoping
(function(numbers){
for(var i=0; i<numbers.length; i++){
(function(i){
setTimeout(console.log, i*2000, i+1)
})(i);
}
})(new Array(10))
OR IIFE and Local Scoping
(function(numbers){
for(let i=0; i<numbers.length; i++){
setTimeout(console.log, i*2000, i+1)
}
})(new Array(10))

for(var i = 0 ; i <= 10 ; i++) {
setTimeout( () => { console.log(i) }, i * 1000 );
}
Why we are not able to print 0 to 10 no with the help of var?
Why we are able to do with let?

You might want to try this:
const printNumbersForEvery2Sec = (n)=>{
for (let i = 1; i <= n; i++) setTimeout(console.log, i * 1000,i)
}
printNumbersForEvery2Sec(10);```

You can use timeout of javascript
function timer(n) {
for (let i = 0; i < 10; i++) {
setTimeout(function () {
console.log(i);
}, i * n);
}
}
timer(2000);
In the above code timing is not coded so you can decide how much interval you want.

A more generalised solution:
function printNumbers(start, end, delay=1){
const interval = delay*1000
for(let i=start; i<=end; i++){
setTimeout(console.log, (i-start)*interval, i)
}
}
printNumbers(3, 10, 2) // firstNumber, lastNumber, timeInSeconds

for (let i = 1; i <= 10; i++) {
setTimeout(() => {
console.log(i)
}, (i * 2000) )
}
Far best! and easy solution... Checkout snippet...
for (let i = 1; i <= 10; i++) {
setTimeout(() => {
console.log(i)
}, (i * 2000) )
}

const RandomUnderHundredNumber = (min,max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; /*min and max numbers are included */
}
let inter
const testFunction = () => {
inter = setInterval(() => console.log(RandomUnderHundredNumber(0,99)), 1000) // generate number between 0 and 99 every 1 sec
}
testFunction();
setTimeout(function( ) { clearInterval(inter); }, 5000); /* clear interval after 5 sec delay (optional) */

const printNumbersForEvery2Sec = (n)=>{
for (let i = 1; i <= n; i++) {
setTimeout( () =>{
console.log(i)
}, i * 2000)
}
}
printNumbersForEvery2Sec(10);

There are two solution to this problem.
Using let keyword, local scope.
const printNumbers = (n) => {
for (let i = 1; i <= n; i++) {
setTimeout( () => {
console.log(i);
}, i * 2000);
}
}
printNumbers(5);
Using var keyword, functional scope with the help of closures.
Wrap the setTimeout function with another function which has the value of the variable at that instance. Which console's log the correct value.
Example is shown below.
const printNumbers = (n) => {
for (var i = 1; i <= n; i++) {
function helper(num){
setTimeout( () => {
console.log(num);
}, num * 2000);
}
helper(i);
}
}
printNumbers(5);

Related

Running the rest code after condition is met

please how can i make the second if condition run after i is greater than 9
var i = 0;
var x = document.querySelector(".start");
x.addEventListener("click", function () {
if (i < 10) {
console.log(i);
i++;
}
})
if (i === 10) {
console.log(i);
}
<button class="start">start</button>
You could move the check inside of the event callback and check if the value is ten, then return early.
Otherwise increment i and make the wanted output.
var i = 0;
var x = document.querySelector(".start");
x.addEventListener("click", function () {
if (i === 10) return;
i++;
if (i < 10) {
console.log(i);
} else {
console.log('ten');
}
})
<button class="start">start</button>

How to run every instance of for loop after 5 seconds?

How to run every instance of for loop after 5 seconds?
I tried the following code but it didn't work
setTimeout(function(){
for (var i = 1; i < 15; i++) {
alert("Okay user"+i);
}
},3000)
Is this what you mean?
for (var i = 1; i < 15; i++) {
setTimeout(function(){
alert("Okay user"+i);
}, i * 5000)
}
(function myLoop(i) {
setTimeout(function() {
console.log('hello user'+i);
if (i++ < (15 - 1)) myLoop(i);
}, 3000)
})(0);

looping from 1 to 50 after the automatic pause for 30 seconds and further looping to 51 to 100 and so on

How do I submit looping from 1 to 10. And then pause for 10 seconds. And then looping from 11 to 20. And so on
Please help me.
Here is the solution for your question:
var count = 0;
function counter (count) {
if(count < 50) {
var limit = count + 10;
for(var i = count; i <= limit; i++) {
console.log(i);
this.count = i;
}
}
}
counter(count);
setInterval(function() {
counter(count);
}, 10000);
Have fun and try to write code by yourself.

how to print value regular interval of time?

I am using closure in java script to print 1-10 value after each 2 sec.In other words first print 1 then wait for two second then print 2 .I used closure but nothing work .
Here is my code.
for (var i = 0; i < 10; i++) {
(function (index) {
setTimeout(function () {
console.log(i);
}, 2000);
})(i);
}
Use setInterval:
function loopWithDelay(callback, delay, max, min) {
var i = min || 0;
if (i <= max) {
var id = setInterval(function() {
callback(i);
if (++i > max) clearInterval(id);
}, delay);
}
}
loopWithDelay(function(i) { console.log(i) }, 2000, 10);
Or use a recursive setTimeout:
function loopWithDelay(callback, delay, max, min) {
var i = min || 0;
if (i <= max) {
setTimeout(function() {
callback(i);
loopWithDelay(callback, delay, max, ++i);
}, delay);
}
}
loopWithDelay(function(i) { console.log(i) }, 2000, 10);
Instead of using setInterval, you can make a function that call itself using setTimeout
(function myFunc(index) {
setTimeout(function() {
console.log(index);
if (index < 10) myFunc(++index);
}, 2000)
})(1);
Please check below snippet.
var i=1;
var interval = setInterval(function(){
if(i<11){
console.log(i);
i++;
}else{
clearInterval(interval);
}
},2000);
You can create a function for it and use recursive setTimeout calls.
function printDelay(current, last, delay) {
console.log(current);
if(++current <= last) {
setTimeout(function() {
print(current, last, delay);
}, delay);
}
}
printDelay(1, 10, 2000);
One option that hasn't been presented here, and one that will probably get closest to executing "on-time," would be to just set all your timeouts at the same time, each having the desired delay before execution. If you have a smaller, fixed number, this should be fine.
for (var i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i + 1); // Add 1 to i for display purposes
}, (i + 1) * 2000); // Execute every 2 seconds starting at 2 seconds
}
This is essentially the same as:
for (var i = 1; i <= 10; i++) {
setTimeout(function() {
console.log(i);
}, i * 2000); // Execute every 2 seconds starting at 2 seconds
}
To start immediately instead of after 2 seconds, the first timeout value just has to come at 0 instead of 2000 (milliseconds).

javascript show in cycle with delay

Simple example:
for (var i = 0; i < 10; ++i) {
console.log(i); // <--- should be show with delay in 300ms
}
Simple setTimeout using of course doesn't work... I guess there's should be using closures..
It's a simple matter of writing a recursive function:
function display(i)
{
if (i == 10) return;
setTimeout(function(){ console.log(i); display(i+1); }, 300);
}
Should do the job:
for (var i = 0; i < 10; ++i) {
(function(i) {
setTimeout(function(){console.log(i);}, i*300);
})(i);
}
You could use setInterval, like so:
var i = 0;
var id = setInterval(function(){
if (i == 9) clearInterval(id);
console.log(i);
i++;
}, 300);
Example here http://jsfiddle.net/MLWgG/2/

Categories

Resources