search
HomeWeb Front-endJS TutorialJavascript 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]);
  • ##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);
  • 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
  • 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 
  • 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);
  • 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/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/013/14c7285aa427c9064d4fe8d1ea51338d-0.png?x-oss-process=image/resize,p_40" 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>
    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();

五、需要注意的点

  • 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
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
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment