Engin Erdoğan
Engin Erdoğan

Reputation: 47

I cant make for loop work in function

I am trying to create a function which puts a text in abc div and with the for loop i want to show 10 random text in that div. I cant make my function work in for loop, it works for once then stops. How can i make it for more?

function myFunction() {
    setTimeout(function () {
        var rand = Math.floor((Math.random() * 100) + 1);
        $("#abc").text(rand);
    }, 1000);
}
$('#start').click(function () {
    for (var i = 0; i < 10; i++) {
        myFunction();
    };
})

Upvotes: 0

Views: 60

Answers (4)

Robert Messerle
Robert Messerle

Reputation: 3032

The issue isn't that your setTimeout is not working, it's that it's setting 10 1-second timeouts at the same time, so they are all firing at the same time 1 second later. What you want to do is stagger your timeouts based on the index of your loop:

function myFunction() {
    var rand = Math.floor((Math.random() * 100) + 1);
    $("#abc").text(rand);
}
$('#start').click(function () {
    for (var i = 0; i < 10; i++) {
        setTimeout(myFunction, i * 1000);
    };
})

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074335

Your loop schedules 10 calls to myFunction, all of which will happen one right after another one second later. If you want to schedule 10 calls to run (say) one per second over the course of 10 seconds, you have to use a different interval for the second, third, fourth, etc.

function myFunction(count) {
    setTimeout(function () {
        var rand = Math.floor((Math.random() * 100) + 1);
        $("#abc").text(rand);
    }, 1000 * count);
}
$('#start').click(function () {
    for (var i = 1; i <= 10; i++) {
        myFunction(i);
    };
})

There I'm passing i into myFunction (as count). Note that I changed the loop to be from 1 to 10 (inclusive) instead of 0 to 9 so that count * 1000 in myFunction would be 1000 for the first loop iteration (since you seemed to want the first one to happen after one second, rather than immediately).

Upvotes: 1

Coby
Coby

Reputation: 1528

Something like this?http://jsfiddle.net/PQmj2/

What you need to do is add a delay between each setTimeout call.

function myFunction(i) {
    setTimeout(function () {
        var rand = Math.floor((Math.random() * 100) + 1);
        $("#abc").text(rand);
    }, 1000 * i);
}
$('#start').click(function () {
    for (var i = 0; i < 10; i++) {
        myFunction(i);
    };
})

What I'm doing here is passing in the value of i to myFunction. That way, there is a delay of 1 second between each call i.e. 1000 * 1 = 1 second, 1000 * 2 = 2 seconds, 1000 * 3 = 3 seconds, and so on.

Upvotes: 1

user887675
user887675

Reputation: 557

setTimeout is calling something delayed. Use setInterval when you want it to repeat.

Upvotes: -1

Related Questions