Page 1 of 1

Satrt/Stop button for loop

Posted: Thu Oct 09, 2014 5:32 am
by AintOnNothing
Hi,

How can one stop a loop once started with a button?

I can start the while loop but can't stop it, the button request is coming from an ajax post

Here's the code:

Code: Select all

	$run=false;
	
	if (isset($_GET['btnRequest']) && !empty($_GET['btnRequest'])){
		
		$btnRequest = $_GET['btnRequest'];
		
		if($btnRequest=="startLoop"){
			$run=true;
			echo "started..";	
		}else if ($btnRequest=="stopLoop"){
			$run=false;
			echo "stopped..";
		}
		
		$count = 0;
		
		while ($run==true){

			echo "looping..<br/><br/>";
				sleep(1);
				$count++;
		}				
	}

Re: Satrt/Stop button for loop

Posted: Thu Oct 09, 2014 5:56 am
by borre
I think you can better use JavaScript in this case ;-)

PHP is server-side, JavaScript is client-side.

Re: Satrt/Stop button for loop

Posted: Thu Oct 09, 2014 6:14 am
by AintOnNothing
borre wrote:I think you can better use JavaScript in this case ;-)

PHP is server-side, JavaScript is client-side.
Any example?

Re: Satrt/Stop button for loop

Posted: Thu Oct 09, 2014 11:23 am
by borre
I've just created this working example for your with JavaScript / jQuery.

I'm a jQuery fan so,.. :-)

Code: Select all

<form method='post' onSubmit='return false;'>
	<input type='button' id='indicator' data-state='start' value='Start'> <input type='button' id='reset' value='Reset timer'>
</form>

<span id='loop'>1</span>

Code: Select all

var counterInterval;
function count(element) {
	var loop = parseInt($('#'+element).text());
	console.log($('#'+element).text(loop+1));
}

$(function() {
	$('#indicator').on('click', function() {
		var state = $(this).data('state');
		var loop = parseInt($('#loop').text());
		if (state == 'start') {
			$(this).data('state', 'stop');
			$(this).val('Stop');
			window.counterInterval = setInterval('count("loop");', 1000);
		} else if (state == 'stop') {
			$(this).data('state', 'start');
			$(this).val('Start');
			clearInterval(window.counterInterval);
		}
	});
	$('#reset').on('click', function() {
		if ($('#indicator').data('state') == 'stop') {
			$('#indicator').trigger('click');
		}
		$('#loop').text('1');
	});
});
I also want to say you need to try things yourself too..
So see if this can help you out a bit.

The jQuery library is downloadable at their website.