Reputation: 2096
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
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.
function start ()
{
clearInterval(interval);
interval = setInterval(function(){++i;}, 1000);
}
function stop ()
{
clearInterval(interval);
output.value = i;
}
Upvotes: 1
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
Reputation: 22951
clearInterval
and setInterval
are methods of window, not document. You can call them as window.clearInterval
or just clearInterval
.Here is a working demo http://jsfiddle.net/9cveg/
Upvotes: 1