1

i cant use setInterval mehod, i don't know why. what's wrong with this script, after clicking on stop it doesn't show the result of counter i in the text field.

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        <title>test_setInterval</title>

        <script type="text/javascript">
            var i = 0;
            var interval;

            function start ()
            {
                interval = document.setInterval("i++", 1000);
            }

            function stop ()
            {
                document.clearInterval(interval);
                output.value = i;
            }
        </script>

    </head>

    <body>
        <input id="output" type="text" />
        <input id="start" type="button" value="start" onclick="start()" />
        <input id="stop" type="button" value="stop" onclick="stop()" />
    </body>
</html>

3 Answers 3

1
  1. clearInterval and setInterval are methods of window, not document. You can call them as window.clearInterval or just clearInterval.
  2. It's better to use function as the first argument for setInterval, not a string with the code, because eval is evil.

Here is a working demo http://jsfiddle.net/9cveg/

Sign up to request clarification or add additional context in comments.

Comments

1

You have to wrap i++ inside a function.
Also, remove document. before the setInterval.
Now, be careful that this has a bug. If you press "start" twice, i will go up by two units every second.
Solved the bug by adding another clearInterval in the start function.

http://jsfiddle.net/46kzu/3/

    function start ()
    {   
        clearInterval(interval);
        interval = setInterval(function(){++i;}, 1000);

    }

    function stop ()
    {
        clearInterval(interval);
        output.value = i;
    }

Comments

0

According to definition, The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds) and its window's method not document's .

 <script type="text/javascript">

                var i = 0;
                var interval;

                function start ()
                {
                    interval = window.setInterval("i++", 1000);
                }

                function stop ()
                {
                    document.clearInterval(interval);
                    output.value = i;
                }

            </script>

1 Comment

This still won't work, setInterval will have 1 as a first argument not method which increments i.

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.