Home > Article > Web Front-end > Javascript timer example code
JS provides some native methods to delay the execution of a certain piece of code. Let’s briefly introduce it
setTimeout
: Set a timer to execute a function or code segment once after the timer expires
var timeoutId = window.setTimeout(func[, delay, param1, param2, ...]); var timeoutId = window.setTimeout(code[, delay]);
- ##timeoutId: timer ID
- func: function executed after delay
- code: code string executed after delay. It is not recommended to use the principle similar to
eval()
- delay: delay time (unit: milliseconds), the default value is 0
- param1, param2: parameters passed to the delay function, supported by IE9 and above
setInterval: Repeatedly call a function or code segment at a fixed time interval
var intervalId = window.setInterval(func, delay[, param1, param2, ...]); var intervalId = window.setInterval(code, delay);
- intervalId : Repeat operation ID
- func: Delayed function call
- code: Code segment
- delay: Delay time, no default value
setImmediate: Execute the specified function immediately after the browser completely ends the currently running operation (IE10 only and implemented in Node 0.10+), similar to
setTimeout(func, 0)
var immediateId = setImmediate(func[, param1, param2, ...]); var immediateId = setImmediate(func);
- immediateId: timer ID
- func: callback
requestAnimationFrame: An API specially designed to implement high-performance frame animation, but the delay time cannot be specified. It depends on the refresh frequency of the browser (frame)
var requestId = window.requestAnimationFrame(func);
The above is simple Four JS timers have been introduced, and this article will mainly introduce the two more commonly used ones:
- func: Callback
setTimeout and
setInterval.
// 下面代码执行之后会输出什么? var intervalId, timeoutId; timeoutId = setTimeout(function () { console.log(1); }, 300); setTimeout(function () { clearTimeout(timeoutId); console.log(2); }, 100); setTimeout('console.log("5")', 400); intervalId = setInterval(function () { console.log(4); clearInterval(intervalId); }, 200); // 分别输出: 2、4、5
setInterval## What is the difference between # and setTimeout
?
// 执行在面的代码块会输出什么? setTimeout(function () { console.log('timeout'); }, 1000); setInterval(function () { console.log('interval') }, 1000); // 输出一次 timeout,每隔1S输出一次 interval /*--------------------------------*/ // 通过setTimeout模拟setInterval 和 setInterval有啥区别么? var callback = function () { if (times++ > max) { clearTimeout(timeoutId); clearInterval(intervalId); } console.log('start', Date.now() - start); for (var i = 0; i
and setInterval
, they only differ in the number of executions, setTimeout
once , setInterval
n times. The difference between
and setInterval
simulated by setTimeout
is: setTimeout
can only be used during the callback The next timer
will be called only after it is completed, and setInterval regardless of the execution status of the callback function, when reaches the specified time, an event to execute the callback will be inserted into the event queue
, so when choosing a timer method, you need to consider whether this feature of setInterval will have any impact on your business code?
or setImmediate(func)
Who is faster? (I wrote this test just out of curiosity)
console.time('immediate'); console.time('timeout'); setImmediate(() => { console.timeEnd('immediate'); }); setTimeout(() => { console.timeEnd('timeout'); }, 0);
and found that setTimeout
was earlier Execution
// 题目一 var t = true; setTimeout(function(){ t = false; }, 1000); while(t){} alert('end'); /*--------------------------------*/ // 题目二 for (var i = 0; i <p></p><p>The answer to the question will be answered later<strong><em></em></strong>3. The working principle of JS timer</p><h2>In explaining the above questions Before answering, let's first understand how the timer works. Here we will use an example from How JavaScript Timers Work to explain the working principle of the timer. This picture is a simple version of the schematic diagram. </h2><p></p><p><img src="https://img.php.cn/upload/article/000/000/013/14c7285aa427c9064d4fe8d1ea51338d-0.png" style="max-width:90%" style="max-width:90%" title="Javascript timer example code" alt="Javascript timer example code">In the above figure, the number on the left represents time in milliseconds; the text on the left represents that after an operation is completed, the browser will ask what is in the current queue waiting to be executed. The operation; the blue square represents the code block being executed; the text on the right represents what asynchronous events occur while the code is running. The general flow of the figure is as follows: </p><p></p>
, mouse click event, setInterval
runs first, the delay time is 10ms, and then After the mouse event occurs, the browser inserts the click callback function into the event queue. Later setInterval
runs. After 10ms arrives, setTimeout
inserts setTimeout## into the event queue. #'s callback
后面浏览器将在执行完当前队头的代码之后,将再次取出目前队头的事件来执行
这里只是对定时器的原理做一个简单版的描述,实际的处理过程比这个复杂。
好啦,我们现在再来看看上面的面试题的答案。
第一题
alert
永远都不会执行,因为JS是单线程的,且定时器的回调将在等待当前正在执行的任务完成后才执行,而while(t) {}
直接就进入了死循环一直占用线程,不给回调函数执行机会
第二题
代码会输出
5 5 5 5 5
,理由同上,当i = 0
时,生成一个定时器,将回调插入到事件队列中,等待当前队列中无任务执行时立即执行,而此时for
循环正在执行,所以回调被搁置。当for循环执行完成后,队列中存在着5个回调函数,他们的都将执行console.log(i)
的操作,因为当前js
代码上中并没有使用块级作用域,所以i的值在for
循环结束后一直为5,所以代码将输出5个5
第三题
这个问题涉及到
this
的指向问题,由setTimeout()
调用的代码运行在与所在函数完全分离的执行环境上. 这会导致这些代码中包含的this
关键字会指向window
(或全局)对象,window
对象中并不存在shout
方法,所以就会报错,修改方案如下:
var obj = { msg: 'obj', shout: function () { alert(this.msg); }, waitAndShout: function() { var self = this; // 这里将this赋给一个变量 setTimeout(function () { self.shout(); }, 0); } }; obj.waitAndShout();
setTimeout
有最小时间间隔限制,HTML5标准为4ms,小于4ms按照4ms处理,但是每个浏览器实现的最小间隔都不同
因为JS引擎只有一个线程,所以它将会强制异步事件排队执行
如果setInterval
的回调执行时间长于指定的延迟,setInterval
将无间隔的一个接一个执行
this
的指向问题可以通过bind
函数、定义变量、箭头函数的方式来解决
The above is the detailed content of Javascript timer example code. For more information, please follow other related articles on the PHP Chinese website!