Reputation: 249
i hava two question : 1 - for function with input value how i can set interval i test this but now working
<script>
function bn(x)
{
alert (x);
}
setInterval("bn(x)",3000);
</script>
<a href="#" onclick="bn(1);">bn 1</a><br>
with setInterval("bn()",3000);
work but show 'undefine' insteadof '1'
an 2- how Set repeat for two value mean when repeat this function i try for new value and function repeat for two value
<script>
function bn(x)
{
alert (x);
}
setInterval("bn(x)",3000);
</script>
<a href="#" onclick="bn(1);">bn 1</a><br>
<a href="#" onclick="bn(2);">bn 2</a>
Upvotes: 0
Views: 450
Reputation: 12443
<script>
function bn(x) {
alert(x);
}
setInterval(function() { bn(1) }, 3000)
</script>
will call bn
every 3 seconds and pass it the value 1
The reason you were getting undefined before is because you were trying to pass x
which (in the code you posted) has never been declared.
The parameters you pass to a function don't have to have the same name as the function arguments..
<script>
var some_var = 1;
function bn(x) {
alert(x);
}
setInterval(function() { bn(some_var) }, 3000);
</script>
Will do the same thing as the previous example but you'll be able to change some_var elsewhere in your script and have that updated value passed into bn.
Upvotes: 0
Reputation: 7722
Okay, I think I understand what you want; see below:
For your first question, what you are currently doing will obviously not work(as you've likely figured out). To fix that, you must use an anonymous function; example below:
<script>
var x = 1;
function bn(x)
{
alert (x);
}
setInterval(function() {
bn(x);
},3000);
</script>
<a href="#" onclick="x = 1;">bn 1</a><br>
<a href="#" onclick="x = 2;">bn 2</a>
As to your second question, see the last two lines above; as the function is already running all you need to control is the value of x
, and make sure you set its scope as general, as opposed to specific to the function in which it is used.
The onclick events set the value of x
. I've made sure the code works; if the value is set to 2
, then the alert will display 2
, etc.
Upvotes: 4