Home  >  Article  >  Web Front-end  >  JavaScript Advanced Tutorial (Lesson 3, Part 2) Page 1/2_Basic Knowledge

JavaScript Advanced Tutorial (Lesson 3, Part 2) Page 1/2_Basic Knowledge

PHP中文网
PHP中文网Original
2016-05-16 19:15:301035browse

To make the timer work in a loop, you need to write a function to implement the loop call. Here is an example:

var the_count = 0;
var the_timeout;
function doTimer()
{
window.document.timer_form.the_text.value = the_count;
> the_count = 2;
the_timeout = setTimeout("doTimer();", 2000);
}

The timer used here is the timer used on the previous page. This function is called when the user clicks the button. This function writes the current value of the_count to the text box. Then the_count is increased by 2, and the function itself is called. The value in the text box is also updated accordingly. When the_count is increased by 2, the function itself is called again. During the two seconds of waiting, the browser can perform other synchronization work. As soon as the_count increases by 2, another setTimeout() is executed. You don't have to worry about memory corruption because there is only one setTimeout() executing at a given time.

The infinite "while" loop will lock the browser's work. During the execution of the loop, the browser cannot execute any other instructions at the same time. And setTimeout allows the browser to perform other work during the gap in the loop.

How to cancel setTimeout?

Now you have learned how to set up an infinite loop. But you have to know how to stop the cycle. Its instruction is clearTimeout. In the above example, the timer also has the following form element:

Click this button to terminate the timer. The command is clearTimeout(), which is actually very simple. If you set setTimeout like this, the_timeout = setTimeout("some javascript",3000);

You can cancel the timer like this: clearTimeout(the_timeout);

Pretty simple, right? Next we look at a complex loop timer, a timer that can report time.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn