SoFunction
Updated on 2025-04-13

JavaScript Advanced Tutorial (Lesson 3) Page 2/2

It's easy to timing events in Javascript. The key instructions are the setTimeout() and clearTimeout() methods. With setTimeout(), the instruction can execute a specific instruction at a specified time in the future. If you change your mind, you can use clearTimeout() to cancel the timing of setTimeout.

The following is the basic format of setTimeout:

    var the_timeout = setTimeout("some javascript statement", some_number_of_milliseconds);

The instructions used in the above example are as follows:
    var the_timeout = setTimeout("alertAndRedirect ();",3000);

There are 3 important contents in this statement:

setTimeout returns a value. In this statement the_timeout is a variable that points to a specific setTimeout.

If you want to cancel the setTimeout timing, you just need to reference the variable. You can give the variable a different name.

The first variable used in setTimeout is a string of a JavaScript statement.

In this example, the first parameter is the string: "alertAndRedirect();"alertAndRedirect is a function written to load a prompt box. When the user clicks "OK", it returns to this page.

Note that the content in the quotes is a complete JavaScript statement with a semicolon and other necessary syntax. If you execute this piece of code, the function lertAndRedirect will be called. setTimeout only specifies the time when the statement appears.

The following is the code of the function alertAndRedirect():

    function alertAndRedirect()
    {
        alert('ok!  exhale!');
        ("");
    }

The second parameter of setTimeout specifies how many milliseconds to execute the first parameter. One second is equal to 1000 milliseconds. So if you want something to happen after 3 seconds you have to set the 2nd parameter to 3,000ms.

We can do the following exercises to get familiar with how it works:

   

The method of making it is to make the button's onClick event call the following function:

    function ringBell()
    {
        var timer1 = setTimeout(".the_form.the_text.value='3 seconds!';",3000);
        var timer2 = setTimeout(".the_form.the_text.value='6 seconds!';",6000);
        var timer3 = setTimeout(".the_form.the_text.value='9 seconds!';",9000);
    }

It means, "From now on, 'three seconds' is displayed after three seconds, 'six seconds' is displayed after six seconds, 'nine seconds' is displayed after nine seconds", it's easy to understand, right?

However, the following does not work:

    function doDumbTimer()
    {
        var timer1 = setTimeout(".the_form_2.the_text_2.value='3 seconds!';",3000);
        var timer2 = setTimeout(".the_form_2.the_text_2.value='6 seconds!';",3000);
        var timer3 = setTimeout(".the_form_2.the_text_2.value='9 seconds!';",3000);
    }

    Try this wrong timing code to see what happens?

   

Note that when you wait for three seconds, one of the three timing messages mysteriously appears in the text box and then stops there. In the bad code above, each setTimeout is executed continuously (that is, "From now on, 'three seconds' is displayed after three seconds, 'six seconds' is displayed after three seconds, 'nine seconds' is displayed after three seconds"). So when three seconds later, all three things happen, and what you get is exactly the final result - of course not the result you hope.

Once you understand, setTimeout() is still quite easy to use. But a difficult question arises: How do you make a timer to make something happen every 2 seconds, from now to forever? Like this example:

   

Don't worry about stopping the timer button first, I'll talk about clearTimeout later. Just think about how you can make the timer loop infinitely. This is actually a very important question and not just a small exercise. As I mentioned earlier, when you use dynamic HTML to make something move slowly on the screen, you execute a timed loop: "Turn a little, wait, move a little more, wait...so like this"

Have you thought of this problem?

OK, the answer is not that simple. You cannot change the content of the text box every two seconds using just one function, like this:

    function theTimer()
    {
        var timer1 = setTimeout("changeTextBoxTo(2);",2000);
        var timer2 = setTimeout("changeTextBoxTo(4);",4000);
        var timer3 = setTimeout("changeTextBoxTo(6);",6000);
        var timer4 = setTimeout("changeTextBoxTo(8);",8000);
        var timer5 = setTimeout("changeTextBoxTo(10);",10000);
        .
        .
        .
    }

Because, OK, you can see why it doesn't work: If you want to use this method to make something loop infinitely, you have to have infinitely many lines of code. Compared to other problems, such as knocking your shoulders and back pain, it takes too long to download a page containing infinite multiple lines of javascript, so this method is not an option at all.

This one doesn't work either, although it looks cooler:

    function theTimer()
    {
        the_time = 0;
        hellIsHot = true;

        while (hellIsHot == true)
        {
            the_time += 2;
            var timer = setTimeout("changeTextBoxTo(the_time);", the_time*1000);
        }
    }

Please study the program for a while and see what results will be obtained. But don't try to run it, otherwise the result will make you very unhappy. Let's take a few trips in the "while" loop:

First time
while (hellIsHot == true) : Yes hell or hot.
the_time += 2 : So now the_time = 2
    var time = setTimeout("changeTextBoxTo(2);", 2000) :
So, two seconds from now on, the text box becomes "2.", which is exactly what we want.

The second time
while (hellIsHot == true) : Indeed, hell is still hot
the_time += 2 : So now the_time = 4

    var time = setTimeout("changeTextBoxTo(4);", 4000) :
So, four seconds from now on, the text box becomes "4.", which is great.

The third time
while (hellIsHot == true) : No, hell is not cool at all.

the_time += 2 : So now the_time = 6

    var time = setTimeout("changeTextBoxTo(6);", 6000) :
So, six seconds from now on, the text box becomes "6." OK.

The fourth time
while (hellIsHot == true) : Yes, it's still hot.

Still that way

Still that way

You understand. This code seems to be done right. Unfortunately, this is not the case. Instead it creates a dead loop, setting setTimeouts until hell gets cold. There are two questions here. First, when in the loop, your browser can't do anything else, basically stop, execute actions, and set the next timer forever. Second, every time you set Timeout, the browser must remember what you are scheduled to execute and when to execute it. Eventually your browser will run out of memory, and then your browser will crash, or your computer will crash, or you will be crazy and never want to write another line of Javascript programs.

Not good at all

Fortunately, there is a way to write a successful timer loop. In the next lecture, we will introduce this method

Previous page12Read the full text