CDW
CDW

Reputation: 33

how to wait one second in my for loop javascript?

Ok I have a random dice number generator. and it will have a for loop and inside the loop I am trouble having to figure out how to wait one second like this below.

Loading. wait one sec Loading.. wait one sec ...

I can do the rest I just need some help with this.

Upvotes: 1

Views: 757

Answers (4)

Mehdi Karamosly
Mehdi Karamosly

Reputation: 5438

You can either use setTimeout or setInterval :

timer = setTimeout(function(){/*your code here */}, 1000);

or

timer = setInterval(function(){/*your code here */},1000);

and once you would like to clear the timer use :

clearTimeout(timer);

or

clearInterval(timer);

Upvotes: 0

Gaurav
Gaurav

Reputation: 1088

In function foo, you can define all stuff that you need to be executed.

var foo = function{
}

var timeout = setInterval(foo, 1000);

and when you want to stop execution

clearInterval(timeout);

Upvotes: 0

Ed Heal
Ed Heal

Reputation: 60007

See https://developer.mozilla.org/en/docs/Web/API/window.setInterval

Will call the function at a particular interval

Upvotes: 0

user1968030
user1968030

Reputation:

Use setInterval:

window.setInterval(func, delay[, param1, param2, ...]);

or setTimeout:

setTimeout(function() {  }, 1000);

'setInterval' vs 'setTimeout':

setTimeout(expression, timeout); runs the code/function once after the timeout.

setInterval(expression, timeout); runs the code/function in intervals, with the length of the timeout between them.

Upvotes: 3

Related Questions