PDA

View Full Version : window.setInterval Question



Ahlahn
01-21-2011, 05:11 PM
Hey guys,

I'm trying to use the setInterval method for a function, but it's not working. Here's the code.



function interval_demo() {
function int_sum() {
alert("I will add two numbers for you, and then add another extra number!");
var n1 = prompt("What's your first number?", "");
var n2 = prompt("What's your second number?", "");
var sum = n1 + n2;
return sum;
}
window.setInterval('int_sum()', 1000);
}
window.onload = interval_demo;


The function works fine if I use window.setInterval('int_sum', 1000). What's the problem with setInterval('int_sum()', 1000)? Correct me if I'm wrong, but isn't that also a valid way to call functions in the setInterval method?

Thanks!

Philip M
01-21-2011, 06:58 PM
Your script has quite a few problems including no way to stop it! Try this:-


<script type = "text/javascript">

function init() {
tim = setInterval(int_sum, 1000); // tim is a global variable
}

function int_sum() {
alert("I will add two numbers for you, and then add another extra number!");
var n1 = parseFloat(prompt("What's your first number?", ""));
var n2 = parseFloat(prompt("What's your second number?", ""));
if (n1!= 0 && n2!= 0) {
var sum = n1 + n2;
if (isNaN(sum)) {
alert ("Invalid values - must be numbers!");
return false;
}
alert ("The sum is " + sum);
}
else {
window.clearInterval(tim);
}
}


window.onload = init;

</script>

There are three ways to call setInterval():-

window.setInterval(fn, 1000);
window.setInterval("fn()", 1000); // it works, but it is obsolete (required for IE browsers before IE5).
window.setInterval(function () {fn()}, 1000);


It's an old-fashioned camera that never lies.