SetTimeOut and setInterval usage in Javascript, and setinterval usage

Source: Internet
Author: User

SetTimeOut and setInterval usage in Javascript, and setinterval usage

The setTimeOut and setInterval of Javascript are used to process latency and scheduled tasks. For example, the pop-up advertisement is automatically closed one minute after the webpage is opened; or the page sends an asynchronous request every 10 seconds to obtain the latest data.

1. setTimeOut () Usage

It is used to call a function or computing expression after a specified number of milliseconds, that is, the internal method is only executed once.


You can use window. settTimeout or setTimeout. The two statements are basically the same.

However, window. setTimeout references the setTimeout function as an attribute of the global window object.

Application instance:

Function reloadTimer () {// do something}; // call the countdown method in the following way: 1 setTimeout ("reloadTimer ()", 1000); // call the countdown method in the following way: 2 setTimeout (reloadTimer, 1000); // call the countdown method 3 (with parameters) setTimeout ('reloadtimer ('+ "'" + param + "'" +') ', 1000 ); // call setTimeout (function () {// do something}, 1000) directly );

2. setInterval () Usage

You can call a function or computing expression by referring to the specified period (in milliseconds ).

SetInterval does not stop calling the function until clearInterval () is called or the window is closed. The ID value returned by setInterval can be used as a parameter of the clearInterval method.

The parameters and usage of the setInterval function are the same as those of the setTimeout function.

Application Instance, countdown to 60 s function:

var count = 60;var countdown = setInterval(function(){if(count <= 1){clearInterval(countdown);}else{count--;}}, 1000);
ClearInterval (countdown) stops calling

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.