phdphd Posted May 3, 2019 Share Posted May 3, 2019 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 ! Quote Link to comment https://forums.phpfreaks.com/topic/308665-triggering-the-same-function-with-some-delay-between-each-run/ Share on other sites More sharing options...
denno020 Posted May 3, 2019 Share Posted May 3, 2019 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 1 Quote Link to comment https://forums.phpfreaks.com/topic/308665-triggering-the-same-function-with-some-delay-between-each-run/#findComment-1566433 Share on other sites More sharing options...
phdphd Posted May 3, 2019 Author Share Posted May 3, 2019 Works like a charm! Quote Link to comment https://forums.phpfreaks.com/topic/308665-triggering-the-same-function-with-some-delay-between-each-run/#findComment-1566434 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.