Jump to content

setinterval working on too many functions.


mike12255

Recommended Posts

So ive started taking a crack at learning javascript/ajax and am trying to make a simple chat box. I got this script *almost* working flawless. What I want to do right now is make the script run my function that loads messages every three seconds. I read online about the setinterval function however this makes my post function post the same item multiple times. Also when you first load a page it doesnt show anything in the chat box for three seconds:

    <script>
    	
    	$(document).ready(setInterval(function() {
		$("#messageContainer").load('chat_process.php?a=load');
		
		$("#formsubmit").submit(function() {
			
			$.post('chat_process.php?a=post', $('#formsubmit').serialize(), function (data){
				document.getElementById('Message').value ="Message";
			});
			return false;
			
		});
		
		},3000));
    </script>

Would it be best practice to make another document.ready and place the post call in that without an interval function?

You don't need a separate document ready handler, you just need to limit what happens in your setInterval callback. You only want the setInterval to load messages, so that is the only bit of code that should be in that function. Your form submit handler would go outside of the interval function.

 

$(function(){ ///shortcut for $(document).ready(function(){
   setInterval(function(){
      //Load messages.  This is the only bit which belongs here.
      $("#messageContainer").load('chat_process.php?a=load');
   }, 3000);

   //The submit handler goes here, outside of the interval function (but inside the ready event)
   $("#formsubmit").submit(function() {
      $.post('chat_process.php?a=post', $('#formsubmit').serialize(), function (data){
         document.getElementById('Message').value ="Message";
      });
      return false;
   });
});

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.