The difference between settimeout and setinterval in JS

Source: Internet
Author: User

Learned a long time of JavaScript, found that the very common two functions, is setinterval and settimeout function, the understanding of these two functions, sometimes feel very vague, after many experiments, finally to it has a more in-depth understanding. Definition, SetInterval ()--interval Specifies the number of milliseconds to execute the specified code continuously. SetTimeout, delay two seconds to call the function, this definition is very simple, but it is not like the literal meaning of the Jane

Many people think that these two methods are similar, but, in fact, they are far from the same.
Because the settimeout (expression, delay time) is executed, after the specified time is delayed after loading, the expression is executed once, remember, the number of times is
The setinterval (expression, interaction time) is not the same, it executes the expression once every specified time from loading
So, it's totally different.

Many people are accustomed to include settimeout in the executed function, and then use settimeout again outside the function to achieve the purpose of timed execution.
In this way, the settimeout outside the function triggers the settimeout again when the function is executed to form a recurring timing effect.

When used, each has its own advantages, using the setinterval, you need to stop the tick trigger manually. The use of nested settimeout in the method, you can no longer call settimeout based on the internal logic of the method is equal to stop the trigger.

In fact, two things can be simulated with each other, the specific use of that, to see the need at that time. Just like for can simulate all loops including branches, but also provides do, and while.  //Every 60 seconds execute myfunction () one time
setinterval ("MyFunction ()", 60000);funcition myFunction () {alert (' MyFunction () ');   }//MyFunction once every 60 seconds ()setTimeout ("MyFunction ()", 60000); Function trigger Required

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.