Home Web Front-end JS Tutorial A brief discussion on setTimeout and setInterval_javascript techniques

A brief discussion on setTimeout and setInterval_javascript techniques

May 16, 2016 pm 03:53 PM
setinterval settimeout

When I was writing the latest code, I saw someone using setTimeout(fun,0) in the project, so I wanted to summarize it. Personal understanding, please point out if there are any mistakes. THX

To understand how JavaScript timers work, you must first understand that the JavaScript engine is single-threaded. This can be understood as the JavaScript engine is a waiter. It has a service queue. All interface element events, scheduled trigger callbacks, and asynchronous request callbacks are queued in this task queue, waiting for processing. All tasks are a minimal unit and do not interrupt processing. In this way, you can understand setTimeout(fun,0). It does not mean that the code will be executed immediately unless the task queue is empty (in fact, there are differences in how each browser actually executes this. Newer browsers actually It may be at 4ms; the older version may be longer, 16ms is also possible). And setTimeout(fun, time) means how long it will take to add the fun callback to this task queue, that is, it will take at least time to execute fun.

For example:

setTimeout(function () {
 console.log(1);
}, 0);
var tem = 0;
for (var i = 1; i < 1000000; i++) {
 tem += i;
};
console.log(2);

Copy after login

Display the result as

Copy code The code is as follows:

2
1

That is to say, when executing setTimeout, the function callback is added to the task queue, but it is not executed immediately because the js engine is still busy processing the current js, and only goes to the task list after this code segment is executed. Get a new task, so the result is to display 2 first and then 1.

The setInterval(fun, time) method is to add fun to the queue at certain intervals. So the question is, what if the execution time of fun is longer than time?

Look at a piece of code

var num = 0;
var time = setInterval(function () {
 var tem = 0;
 for (var i = 1; i < 99999999; i++) {
 tem += i;
 };
 num ++;
 console.log(num);
}, 100);

setTimeout(function (){
 clearInterval(time);
}, 1000);

Copy after login

It means to execute a piece of code every 100ms and clear the timer after 1s. But what about the result?

The result is displayed as

Copy code The code is as follows:

1
2
3

In other words, in fact, it has not been executed that many times. That is to say, some intervals will be skipped, so the interval between multiple code executions may be smaller than expected. It turns out that when the timer code is added to the queue, if the timer code instance exists, the timer code will be skipped.

Quoting a picture will make it easy to understand.

The above is the entire content of this article, I hope you all like it.

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 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
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)

What is the difference between settimeout and setinterval What is the difference between settimeout and setinterval Aug 15, 2023 pm 02:06 PM

The difference between settimeout and setInterval: 1. Trigger time, settimeout is one-time, it executes the function once after setting the delay time, while setinterval is repetitive, it will execute the function repeatedly at the set time interval; 2. Execution times, settimeout is only executed once, and setinterval will be executed repeatedly until canceled.

How to use setInterval function to execute code regularly? How to use setInterval function to execute code regularly? Nov 18, 2023 pm 05:00 PM

How to use setInterval function to execute code regularly? In JavaScript, the setInterval function is a very useful function, which can execute a piece of code regularly. Through the setInterval function, we can repeatedly execute specified code within a specific time interval. This article will introduce in detail how to use the setInterval function and provide specific code examples. 1. The basic syntax of the setInterval function is as follows: setInterv

How to use the Window.setInterval() method How to use the Window.setInterval() method Aug 31, 2023 am 09:33 AM

The basic syntax of the Window.setInterval() method is "window.setInterval(function, delay)", function is the function or code block to be executed repeatedly, and delay is the time interval between each execution, in milliseconds. This method is a method in JavaScript used to repeatedly execute a specified function or code at a scheduled time. Its use is very simple. You only need to pass in the function or code block to be executed and the time interval for repeated execution.

How to stop setInterval How to stop setInterval Dec 11, 2023 am 11:39 AM

You can use the clearInterval function to stop a timer created by the setInterval function. The setInterval function returns a unique timer ID, which can be passed as a parameter to the clearInterval function to stop the execution of the timer.

Detailed explanation of setinterval usage Detailed explanation of setinterval usage Sep 12, 2023 am 09:55 AM

The usage of setinterval is "setInterval(function, delay);", "function" is the function to be executed, which can be a function expression or function reference, and "delay" is the time interval between executing functions, in milliseconds. setInterval is a function in JavaScript that is used to execute code periodically. It accepts a function and a time interval as parameters, and will execute the function repeatedly according to the specified time interval.

setInterval setInterval Aug 02, 2023 am 10:17 AM

The setInterval function is a timer function in JavaScript that allows you to set an interval and execute specified code after each interval. It is very useful when certain tasks need to be processed regularly or page elements are updated in real time. Pay attention to the following when using setInterval performance and reliability issues and optimize as needed.

What is the difference between setTimeout() and setInterval() in JavaScript? What is the difference between setTimeout() and setInterval() in JavaScript? Sep 01, 2023 pm 03:01 PM

setTimeout(function,duration) - This function calls the function after duration milliseconds. This works for one execution. Let's see an example - it waits for 2000 milliseconds and then runs the callback function alert('Hello') - setTimeout(function(){alert('Hello');},2000); setInterval(function,uration) - this function is The function is called after every duration milliseconds. This can be done an unlimited number of times. Let's see an example - it triggers an alarm every 2000 ms

Use the clearTimeout function in JavaScript to cancel the setTimeout timer Use the clearTimeout function in JavaScript to cancel the setTimeout timer Nov 18, 2023 am 08:05 AM

To use the clearTimeout function in JavaScript to cancel the setTimeout timer, you need specific code examples. In JavaScript, the setTimeout function is used to execute a specific code after a specified time delay. The setInterval function is used to repeatedly execute a specific code within a specified time interval. However, in some cases we may need to cancel the timer before it executes. In this case, you can use c

See all articles