SetTimeout and setInterval in js

Source: Internet
Author: User

SetTimeout and setInterval in js
SetTimeout and setInterval

Javascript is run in the javascript engine of the browser in a single thread mode,
The functions of setTimeout and setInterval are to insert the code you want to execute into a code queue maintained by the js engine at a specified time point.

The following methods are used for window objects:
SetTimeout () and clearTimeout ()
SetInterval () and clearInterval ()

 

1. Pay attention to the scope during use

If you need to use a timer inside the object to execute a method of the object, you need to pay attention to it.

 

function Game () {}Game.prototype = {constructor: Game,init: function(){clock = setInterval(function(){            this.update();        }, 500);},update: function(){console.log("test");}}var game = new Game();game.init();
The above write method will show Uncaught TypeError: this. update is not a function
The reason is that setInterval () belongs to the window object method. Here this refers to the window object,
The update method is not defined in the window object, so an error is reported.

 

 

function Game () {}Game.prototype = {constructor: Game,init: function(){var that = this;clock = setInterval(function(){            that.update();        }, 500);},update: function(){console.log("test");}}var game = new Game();game.init();
In this way, there will be no problem in writing. var that = this; this sentence means to use that to save the Game object,
If you execute that. update (), there will be no problem.

 

 

In fact, this is also acceptable, but it is difficult to pass parameters.

function Game () {}Game.prototype = {constructor: Game,init: function(){var that = this;clock = setInterval(that.update, 500);},update: function(){console.log("test");}}var game = new Game();game.init();

In addition, you can use closures.

 

 

function Game () {function update(){console.log("test");console.log(this);//window}setInterval(update, 500);}Game();

 

Ii. In-depth analysis of execution principles

 

SetTimeout (callback, time) initializes a timer,
Call back the callback function after the specified time interval.

SetInterval (callback, time) also initializes a timer,
However, it cyclically executes the callback function callback every specified time interval, in milliseconds.

To execute a method consecutively, you can use either of the following methods:
If you do not want continuous calls to cause mutual interference, use setTimeout () nesting,
If you want to accurately execute an action at a fixed time, use setInterval ()

 

//1.setTimeout(function() {a();setTimeout(arguments.callee, time);}, time);//2.setInterval(function(){a();}, time);

For example:
If the execution of the () method requires 10 s, and the time is equal to 3 s, let's analyze the differences between the two methods.

 

1.
If the () method is executed for 10 s, the time of setTimeout In the first callback execution is also 10 s, and setTimeout is executed.
Function, probably means sending a message to the browser. "Hi, man, it takes 3 seconds for me to insert a message to the Code queue.
The code of the () method ". Because the setTimeout method in callback does not have the code to be executed, the three seconds
The cpu is actually in idle state, so after 3 seconds, the code will be inserted, and because the current cpu is idle, you can immediately execute
A () method, the time has reached 13th s.
Therefore, it takes 13 s to execute a period in this way.



2.
Because time is equal to 3 s, a new a () code is inserted into the code queue in 3 s, 6 s, and 9 s,
However, because the js engine only allows one unexecuted a () code, this is not the case.
When the first 10 s, the () method is being executed, the new a () code is inserted only 3 s.
To the code queue, others will be ignored. When method a () is executed within 10 s, the code of the () method inserted at 3 s will start to run.
The Code insertion time has nothing to do with the code execution time.
Therefore, it takes 10 s to execute a cycle in this way.




Of course, by the way, the execution time of a function is not fixed.
There are some deviations, but they are probably stable near a certain value, which is related to the internal running policy of the cpu. This is far away.

 

Related Article

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.