Understand the setTimeout and setInterval In the javascript timer, and the js timer setinterval.
I. Explanation
1. Overview
SetTimeout: Call a function or execute a code snippet after the specified Delay Time
SetInterval: periodically calls a function or executes a piece of code.
2. Syntax
SetTimeout:
var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);var timeoutID = window.setTimeout(code, delay);
- TimeoutID is the numeric ID of the delayed operation. This ID can then be used as a parameter of the window. clearTimeout method.
- Func is the function you want to execute after delay in milliseconds.
- Code in the second syntax refers to the code you want to execute after delay milliseconds
- Delay is the number of milliseconds of delay (one second equals 1000 milliseconds). function calls will occur after the delay, but the actual delay may be a little longer.
- Standard browsers and IE10 support the ability to pass additional parameters to latency functions in the first syntax
SetInterval
var intervalID = window.setInterval(func, delay[, param1, param2, ...]);var intervalID = window.setInterval(code, delay);
- IntervalID is the unique identifier of this repeated operation and can be passed as a parameter to clearInterval ().
- Func is the function you want to call repeatedly.
- Code is another syntax application. It refers to the code consisting of a string that you want to repeat.
- Delay is the number of milliseconds of each delay (one second equals 1000 milliseconds). Each function call will occur after this delay. Like setTimeout, the actual latency may be a little longer.
- Standard browsers and IE10 support the ability to pass additional parameters to latency functions in the first syntax
<script type="text/javascript"> setTimeout( function(param){ alert(param)} , 100, 'ok'); </script>
I tested the fifth article in a simple way and used firefox and IE9 tests on my computer respectively. The former can bring up OK and the latter can bring up undefined.
Ii. "this" Problem
The Code called by setTimeout () runs in the execution environment completely isolated from the function. this causes the this keyword in the code to point to the window (Global Object) object, which is different from the expected value of this. SetInterval is similar.
<Script type = "text/javascript"> // this points to window function shape (name) {this. name = name; this. timer = function () {alert ('My shape is '+ this. name)}; setTimeout (this. timer, 50);} new shape ('rectang'); </script>
Not passed in. This is the result of chrome, firefox, and IE9 experiments.
Solution 1:
<script type="text/javascript"> function shape(name) { this.name = name; this.timer = function(){alert('my shape is '+this.name)}; var _this = this; setTimeout(function() {_this.timer.call(_this)}, 50); } new shape('rectangle');</script>
Set a local Variable _ this and put it in the setTimeout function variable. timer executes call or apply and sets the value of this.
Function can call the local Variable _ this, thanks to the closure of Javascript. It involves the scope chain and other knowledge. If you are interested, you can solve it by yourself. It will not be expanded here.
Solution 2:
This method is a little tall. SetTimeout and setInterval are customized. In addition, the earlier version of IE browser is extended and does not support passing additional parameters to the latency function.
<Script type = "text/javascript"> // customize setTimeout and setInterval var _ nativeST _ = window. setTimeout, _ nativeSI _ = window. setInterval; window. setTimeout = function (vCallback, nDelay/*, argumentToPass1, argumentToPass2, etc. */) {var oThis = this, returns GS = Array. prototype. slice. call (arguments, 2); return _ nativeST _ (vCallback instanceof Function? Function () {vCallback. apply (oThis, callback GS) ;}: vCallback, nDelay) ;}; window. setInterval = function (vCallback, nDelay/*, argumentToPass1, argumentToPass2, etc. */) {var oThis = this, returns GS = Array. prototype. slice. call (arguments, 2); return _ nativeSI _ (vCallback instanceof Function? Function () {vCallback. apply (oThis, callback GS) ;}: vCallback, nDelay) ;}; function shape (name) {this. name = name; this. timer = function (other) {alert ('My shape is '+ this. name); alert ('extra param is '+ other) ;}}var rectangle = new shape ('rectang'); setTimeout. call (rectangle, rectangle. timer, 50, 'other'); </script>
1. Set local variables and assign values to native setTimeout and setInterval
2. Extended setTimeout and setInterval. The parameter GS obtains an additional parameter array by splitting the arguments variable.
3. Use vCallback instanceof Function to determine whether it is a Function or code. If it is a Function, use apply to execute it.
4. setTimeout is executed with call, And this object and other parameters such as func and delay are set.
5. By the way, setTimeout can be extended, and additional parameters can be executed in earlier IE browsers.
Iii. Difference Between setTimeout and setInterval
<script type="text/javascript"> setTimeout(function(){ /* Some long block of code... */ setTimeout(arguments.callee, 100); }, 10); setInterval(function(){ /* Some long block of code... */ }, 100);</script>
It seems that the two functions are similar, but they are actually different.
The interval between the execution of the setTimeout callback function and the last execution is at least 100 ms (more may occur, but not less than 100 ms)
The callback function of setInterval will try to run every Ms. no matter whether the last execution is completed or not, the interval is theoretically set to <= delay.
SetInterval:
<script type="text/javascript"> function sleep(ms) { var start = new Date(); while (new Date() - start <= ms) {} } var endTime = null; var i = 0; setInterval(count, 100); function count() { var elapsedTime = endTime ? (new Date() - endTime) : 100; i++; console.log('current count: ' + i + '.' + 'elapsed time: ' + elapsedTime + 'ms'); sleep(200); endTime = new Date(); }</script>
From firebug in firefox, we can see that the time interval is very irregular.
The general situation is as follows: Because the execution time of the count function is much higher than the scheduled interval of setInterval, the thread that is triggered regularly will continuously generate asynchronous scheduled events, and put it at the end of the task queue, regardless of whether they have been processed, but once a scheduled event task is processed, the remaining scheduled events in the arrangement will be executed continuously.
SetTimeout:
<script type="text/javascript"> function sleep(ms) { var start = new Date(); while (new Date() - start <= ms) {} } var endTime = null; var i = 0; setTimeout(count, 100); function count() { var elapsedTime = endTime ? (new Date() - endTime) : 100; i++; console.log('current count: ' + i + '.' + 'elapsed time: ' + elapsedTime + 'ms'); sleep(200); endTime = new Date(); setTimeout(count, 100); }</script>
The above is all of the content in this article, hoping to help you learn javascript timers.
Articles you may be interested in:
- Example for the setInterval/setTimeout Function of javascript
- Difference between javascript setTimeout and setInterval
- Use of JavaScript setTimeout and setInterval
- Code of Js setInterval and setTimeout (scheduled execution and cyclic execution) (parameters can be passed in)
- This introduction of setTimeout and setInterval in Javascript objects
- When setTimeout () and setInterval () are called and executed in Js
- In JS, setInterval and setTimeout cannot pass functions with parameters.
- Differences between javascript setTimeout and setInterval timing
- How to use JavaScript SetInterval and setTimeout
- SetInterval and setTimeout instances in js