MTVS
MTVS

Reputation: 2096

can't use javaScript setInterval method

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>

Upvotes: 1

Views: 336

Answers (3)

XCS
XCS

Reputation: 28177

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;
    }

Upvotes: 1

Ashwin Singh
Ashwin Singh

Reputation: 7375

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>

Upvotes: 0

bjornd
bjornd

Reputation: 22951

  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/

Upvotes: 1

Related Questions