Jump to content

won't stop executing


matthew9090

Recommended Posts

ive got this code:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
	$(document).ready(function() {
	  var number = 5;
	  function countdown() {
				setTimeout(countdown, 1000);
				$('#box').html("Selecting person in " + number + " seconds");
				number --;

				if (number<0) {
				keywords = 
				[
				"name1", 
				"name2",
				"name3",
				"name4",
				"name5"
				]
					var keyword = keywords[Math.floor(Math.random()*keywords.length)]
					document.write(keyword);
					number = 0;
				}
	  }
	  countdown();
	});
</script>
<center>
<div id="box">
</div>
</center>

 

it counts down from 5 then chooses a random name but then keeps doing it every second and there is a huge line of names. how can i stop this?

 

Link to comment
https://forums.phpfreaks.com/topic/232853-wont-stop-executing/
Share on other sites

That's because on every call to countdown() you're creating another timer, so it will keep running infinitely. You can either create an else clause for your if statement, and move the setTimeout call there - terminating the loop once the name is selected. Or you could use setInterval(), and then clearInterval() once a name is selected.

Link to comment
https://forums.phpfreaks.com/topic/232853-wont-stop-executing/#findComment-1197688
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.