Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.