Reputation: 61
Can any body shed some light on why I am not able to stop and start this loop?
<input type="button" value="start" onclick="start()">
<input type="reset" value="stop" onClick="stop()">
var startLottery = false;
while(startLottery){
setInterval(function(){automateLottery()},120);
startLottery;
};
var start = function(){
startLottery = true;
};
var stop = function(){
startLottery = false;
};
Thank you
Upvotes: 1
Views: 67
Reputation: 6571
Problem 1
A while
loop will only execute when the operand evaluates to true
.
However, you start off with your startLottery
variable equal to false
.
So the while
loop will never execute.
Problem 2
At no point are you actually changing the value of the startLottery
variable, so even if the loop did execute, it would never terminate.
Upvotes: 2
Reputation: 516
If what you provided for code is exactly as I see it, the while
loop will never be entered. The page will be rendered (the input
s) and then the variable startLottery
will be set to false
. Next, the loop will evaluate the expression (which will always return false
) and never actually enter the loop.
Upvotes: 0
Reputation: 46657
You cannot start and stop a loop like that. You need to use setInterval
and clearInterval
:
JS:
var lotteryInterval;
var start = function(){
lotteryInterval = setInterval(lotteryFunc, 120);
};
var stop = function(){
clearInterval(lotteryInterval);
};
var lotteryFunc = function () {
automateLottery();
};
HTML:
<input type="button" value="start" onclick="start()">
<input type="reset" value="stop" onClick="stop()">
Edit: Working demo.
Upvotes: 2
Reputation: 71939
I believe you're looking for this (assuming you do have an automateLottery
function):
var timer;
var start = function(){
timer = setInterval(automateLottery, 120);
};
var stop = function(){
clearInterval(timer);
};
start();
Upvotes: 0