Home > Web Front-end > JS Tutorial > body text

Javascript timer example code

高洛峰
Release: 2017-03-19 17:14:00
Original
1626 people have browsed it

1. What is a timer

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]);
Copy after login
  • ##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);
Copy after login
  • 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);
Copy after login
  • 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);
Copy after login
  • func: Callback

The above is simple Four JS timers have been introduced, and this article will mainly introduce the two more commonly used ones:

setTimeout and setInterval.

2. Give a chestnut

  • Basic usage

// 下面代码执行之后会输出什么?
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
Copy after login
  • 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 
    Copy after login
  • If it is
setTimeout

and setInterval, they only differ in the number of executions, setTimeout once , setIntervaln times. The difference between

setInterval

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?

  • setTimeout(func, 0)

    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);
    Copy after login
  • was tested in
Node.JS v6.7.0

and found that setTimeout was earlier Execution

  • Interview questions

  • What is the result after running the following code?
// 题目一
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>
Copy after login
    When the program starts, a JS code block begins to execute, and the execution time is about 18ms. During the execution process, 3 asynchronous events are triggered, including one
  • setTimeout

    , mouse click event, setInterval

  • The first
  • setTimeout

    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

    When the first code block is executed, the browser checks what events are waiting in the queue, and it takes out the code at the front of the queue to execute
  • When the browser processes the mouse click callback,
  • setInterval
  • checks the arrival delay time again, and it will insert an interval callback into the event queue again, and then every specified interval After the delay time, a callback will be inserted into the queue

  • 后面浏览器将在执行完当前队头的代码之后,将再次取出目前队头的事件来执行

这里只是对定时器的原理做一个简单版的描述,实际的处理过程比这个复杂。

四、题目答案

好啦,我们现在再来看看上面的面试题的答案。

第一题

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();
Copy after login

五、需要注意的点

  • 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template