Jump to content

Triggering The Same Function With Some Delay Between Each Run


phdphd

Recommended Posts

Hi All,

I have a function that I want to trigger multiple times on different parts of the document, with a 1 second delay between each run.

The structure of the function is as follows

function intro(param1, param2){

//processing goes here

};

 

I call it like this :

$(document).ready(function(){

intro('#hello', '#world');

intro('#hi', '#all');

intro('#hola', '#amigos');

});

I would like to trigger intro('#hi', '#all') 1 second after intro('#hello', '#world') starts, and intro('#hola', '#amigos') 1 second after intro('#hi', '#all') starts, and so on.

 

Thanks !

Link to comment
Share on other sites

You're going to want to make use of setTimeout. The syntax is as follows:

	setTimeout(function() {
	  // Execute this code after the timeout of 1000ms
	}, 1000);
	

Keep in mind that this function is asynchronous, which means

	$(document).ready(function(){
	  setTimeout(function() {
	    intro('#hello', '#world');
	  }, 1000);
	 
	  setTimeout(function() {
	    intro('#hi', '#all');
	  }, 1000);
	 
	  setTimeout(function() {
	    intro('#hola', '#amigos');
	  }, 1000);
	});
	

Will execute all into functions after 1 second.

This could be a solution:

	$(document).ready(function(){
	  setTimeout(function() {
	    intro('#hello', '#world');
	  }, 1000);
	 
	  setTimeout(function() {
	    intro('#hi', '#all');
	  }, 2000);
	 
	  setTimeout(function() {
	    intro('#hola', '#amigos');
	  }, 3000);
	});
	

However that will quickly fail if the execution of the next function has to be 1 second after the previous function has finished (assuming there might be some delays/user input/processing inside the intro function)

Hopefully that's enough information to get you on the right track to figuring it out

  • Thanks 1
Link to comment
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.