Table of Contents
1. What is a timer
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.
四、题目答案
五、需要注意的点
Home Web Front-end JS Tutorial Javascript timer example code

Javascript timer example code

Mar 19, 2017 pm 05:14 PM
javascript

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 id="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">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="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/013/14c7285aa427c9064d4fe8d1ea51338d-0.png" class="lazy"    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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles