Solved

How to force javascript function to wait or sleep for 3 seconds (3000ms) before executing another function

Posted on 2011-02-24
17
1,053 Views
Last Modified: 2013-12-13
I have a function that calls ajax to load contents of a class into a div element. When I set this function to activate from a button on the page, it works as it should. <input type="button" value="load class" onclick="allOpen()" />

This works ok as the button is on the actual page that the div is on so ajax returns the content into that div. My problem is, I only want this function to run once the page is loaded so I have put the code on another button that actually loads this page, That button looks like this...

<input type="button" value="Classes" onclick="loadContent('classes')" />

When that button is clicked, it causes php to include another page called "classes.php". So far so good. But when I add the other function to this button (allOpen()), it does nothing. Here is the modified button.

<input type="button" value="Classes" onclick="loadContent('classes');allOpen()" />

So when clicked it should 1: load the classes page and 2: run the 2nd function allOpen() which loads content into a <div> element. This is not working and I think I know why. I think that it is calling the 2nd function before the page is fully loaded so that <div> does not exist yet. Once the page is loaded of course the function works as it should. I have tried a "wait" function to force javascript to wait 3000 milli-seconds before calling the 2nd function but it waits then the screen flashes but nothing changes after the 3 seconds. Can anyone figure out what is going wrong here?

Here is the allOpen function.

function allOpen()
{
ajax.post('search_classes.php',displayResults, 'searchIn=allOpen');
}
// and the displayResults()

function displayResults(result)
{
var mod = document.getElementById('mod-results');
mod.innerHTML = result;
document.getElementById('results').style.display = "inline"; // displays the contents of search_classes.php
setFocus('search');
}
0
Comment
Question by:Mark Brady
17 Comments
 
LVL 11

Expert Comment

by:patsmitty
ID: 34976975
window.setTimeout(function, x);

Where 'function' is the function you want to run after x milliseconds.
0
 
LVL 17

Expert Comment

by:shinuq
ID: 34977166
try this, you need to repalce the string

'nameofdivinthecclassespage' with appropriate name
onclick="startwork()" />

function startwork(){

loadContent('classes');
chkload();
allOpen();
}

function chkload(){
   if(!$('nameofdivinthecclassespage').is(':visible')) settimeout(1000,"chkload");
}

Open in new window

0
 
LVL 10

Expert Comment

by:P1ST0LPETE
ID: 34977248
patsmitty is right, if you simply want to pause for 3 seconds before running a function, you use setTimeout().
Example:

function loadContent(contentName)
{
        //your other code.....
       
        //then call allOpen() at the end of this function
        setTimeout("allOpen()", 3000);
}

or in your button, do it like this:

<input type="button" value="Classes" onclick="loadContent('classes');setTimeout('allOpen()', 3000);" />

0
 
LVL 82

Expert Comment

by:leakim971
ID: 34978960
0
 
LVL 20

Author Comment

by:Mark Brady
ID: 34984476
Thanks for all your help. Like I said, I have tried setting a timeout already with no luck. Just to be perfectly clear, I tried P1ST0LPETE's suggestion: On my "classes" navigation button I put this:

<div class='menu-item' onclick=\"loadPage('admin-classes');setTimeout('allOpen()',3000);\">Classes</div>

This does not work. In fact, I change the code in the allOpen() function to this for testing;

function allOpen()
{
alert('hello');
}

So I removed the ajax call just to be sure the first function is actually getting to the allOpen() function and it is not. No alert !  Could it be that I am using a <div> for my button instead of a <input type='button' ? I will try and change it to an input element instead if a div.
0
 
LVL 20

Author Comment

by:Mark Brady
ID: 34984529
No, it doesn't  work when I change it to an input button. I will do a small example and see if I can replicate the problem. I will post my results here so we can all try testing it.
0
 
LVL 20

Author Comment

by:Mark Brady
ID: 34985554
Ok I have made up a test page so you can see the problem. Put the 3 files in a directory and load the "test.php" page. If you click the "classes" button it will load a div with some data in it. If you then click the middle button "Load in 3 seconds" it will behave properly and load the next content in 3 seconds. But, if you reload the page from scratch "text.php" then click the "delayed classes" button, it will load the classes div but it will not load the other div in 3 seconds, even though that div is now on the page! Well the results are loaded into <div id='results'></div>  but that div is loaded in the first function so in theory it should be already on the page and waiting for the next content, but this does not happen. Why? test.php search.php classes.php
0
 
LVL 20

Author Comment

by:Mark Brady
ID: 34985950
I'm sorry, I forgot to post the ajax mini library I use. you will need this to make the ajax call work. miniajax.js
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 20

Author Comment

by:Mark Brady
ID: 35005047
Any takers?
0
 
LVL 82

Expert Comment

by:leakim971
ID: 35006484
Any live link ?
0
 
LVL 20

Author Comment

by:Mark Brady
ID: 35012033
http://www.bnsrecords.net/EE/test.php

Go there and click the first button (classes) it will show a div with data in it. Then try button 2 "Load in 3 seconds" that will load yet another div underneath with data in it. So far so good. Now try button 3 "Delayed classes" that should run the code on button 1 then after a setTimeout() after 3 seconds should run the code on button 3 but it doesn't. I think it has something to do with ajax. It may be NOT really waiting to execute the code and trying to put data into a div that does not exist yet. If this is the case, is there a fix for this or a better way to do it?

My actual project requires a button which loads certain info into a results div. This works on it's own when clicked, but I need it to run when a different button is clicked. That button loads a different div with other information in it (like my example), but I need it to then load the classes info as well but only when this button is clicked. I did add a line of code on the page which ran the code and loaded the classes info but I don't want that to happen EVERY time the page is refreshed. It only needs to run when the user clicks the "Classes" button  to load that page. The classes stuff that gets loaded is in a "include()" line so it includes the file with the classes div and the results div inside it. Confused?

See what you think.
0
 
LVL 82

Expert Comment

by:leakim971
ID: 35012807
your first button reload the page with a parameter (loc) saying you want to display the div with data in it : window.location = 'test.php?loc=' + loc;
your second button use ajax to load the div underneath with data in it

you third button reload the page, your code is stopped, so you loose your timer and the click on the second button

you should use ajax for the first button too
0
 
LVL 20

Author Comment

by:Mark Brady
ID: 35013182
you third button reload the page, your code is stopped, so you loose your timer and the click on the second button

This does not matter. You should be able to go to that test page and click ONLY button 3. That button runs two functions. The first function is the same as button 1 and the second function is then executed from button 3 which delays the loading of more data. So if I took off the first two buttons (only put there for demonstration) the page should still work with only the third button. 1 button that runs two functions. Why won't this work? The timer is not started until you click button 3 and the first function has run.
0
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 35013203
>Why won't this work? The timer is not started until you click button 3 and the first function has run.

Because, when reloading the page, your code start from scratch. That's why Ajax is so popular, it allow you to load data without reloading/refreshing the page
0
 
LVL 20

Author Comment

by:Mark Brady
ID: 35013278
Ahhh so when the page reloads as on the first function, are you saying it never gets to run the code that comes after this?
0
 
LVL 82

Expert Comment

by:leakim971
ID: 35013296
Yes as if you load the page the first time :)
0
 
LVL 20

Author Closing Comment

by:Mark Brady
ID: 35013354
I can't believe it was that simple. Thank you so much. I never even looked at the fact that the page was reloading and therefore not running the second function - so simple!
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now