1

I am very new to JavaScript and cannot seem to get the setTimeout command to do anything. I know this has been asked many times before, but I have spent the last two hours looking at all previous cases of it and it still isn't working for me. Here is what I have got at the moment:

<html>
    <script type="text/javascript">

    var i = 0;
    function aloop() {
        document.write(i);
        i++;
    }

    function afunction() {
        if (i <= 12) {
            setTimeout(aloop(), 1000);
            afunction();
        }
    }

    </script>

    <form>
    <input type=submit value="Click me!" onClick="afunction()">
</html>

Can anyone tell me what I should do to make this work?

1
  • In addition to the answers, look into using a regular for loop. Commented Dec 6, 2012 at 20:55

3 Answers 3

4

Pass a function to setTimeout, not the return value of a function call.

setTimeout(aloop,1000);
Sign up to request clarification or add additional context in comments.

Comments

1

The problem is you're calling your function instead of queuing your function.

setTimeout(aloop, 1000) NOT setTimeout(aloop(), 1000);

Comments

1

You didn't describe what doesn't work, but I'll assume you want the i to be written in 1000 millisecond intervals.

Do this:

<html>
 <!-- you're missing your head tags -->

<head>
    <title> my page </title>

    <script type="text/javascript">
    var i=0;
    function aloop() {
          // don't use document.write after the DOM is loaded
        document.body.innerHTML = i;
        i++;
        afunction(); // do the next call here
    }
    function afunction() {
        if (i<=12) {
                 //     v---pass the function, don't call
            setTimeout(aloop,1000);

      //    afunction();  // remove this because it'll call it immediately
        }
    }
    </script>
</head>

<!-- you're missing your body tags -->
<body>
    <form>
        <input type=submit value="Click me!" onClick="afunction()">
    </form> <!-- you're missing your closing form tag --> 
</body>
</html>

1 Comment

Thanks everyone for all your help. It's working as I want it to now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.