I know timers has been for a while a feature that a lot of folks use in their day-to-day tasks. In the JavaScript world, timers are often implemented with the setTimeout or setInterval functions, the bad news for you if you are doing it is that it's not a good practice and I will try to explain why.
Before I begin to explain my thought, I have a question for you: can you use a watch giving the wrong time ?
If your answer is yes, I'm sorry to have wasted your precious time because this article does not belong to you.
On the other hand, if your answer is negative, I will explain why using setTimeout or setInterval is like using a damaged watch to get the time.
The problem with these functions
To begin, let's consider the following snippet
function test() { let i = 0; setTimeout(() => console.log("hello"), 0); while (i <p>if you run this snippet in your browser console, you will have the following result </p> <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172346055793207.gif?x-oss-process=image/resize,p_40" class="lazy" alt="You don"></p> <p>This behavior is due to the fact that setTimeout is adding the callback in the browser's queue so that it should process it once it is idle <em>(does not have a task to do)</em> in other words the callback passed to the setTimeout has low priority</p> <p>Now, knowing this, I imagine that it will be hard for you to implement timers using the setTimeout function because you can have 2 or even 10 ticks (depending on how busy your browser is) at the same time. This will be a nightmare to debug, but do we have a better solution ?</p> <h2> A way to avoid these functions </h2> <p>To provide a better way of implementing timers, we should use requestAnimationFrame function because it tells the browser to execute a callback before the next paint <em>(in other words before any change in the UI occurs)</em></p> <p>The difference here is pretty subtle, so it's better to understand it through the code. Let's take back our previous snippet and tweak it a little bit to compare setTimeout and requestAnimationFrame<br> </p> <pre class="brush:php;toolbar:false">function testWithAnimationFrame() { let i = 0; setTimeout(() => console.log("hello"), 0); requestAnimationFrame(() => console.log("tell me the next paint")); while (i <p>In this example, we can see that when running on Chrome, the setTimeout runs before requestAnimationFrame <em>(though in some rare cases the inverse happens)</em></p> <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172346055845434.gif?x-oss-process=image/resize,p_40" class="lazy" alt="You don"></p> <p>But if you run it on Firefox, this will be the output</p> <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172346055919561.gif?x-oss-process=image/resize,p_40" class="lazy" alt="You don"></p> <p>This can seem confusing but if you pay a bit of attention, you will realize that no painting is happening during the execution, so how this scenario is handled depends on the browser.</p> <p>Now if we can tweak our snippet to make the browser repaint the page, let's see what will happen<br> </p> <pre class="brush:php;toolbar:false">function testWithAnimationFrame2() { let i = 0; setTimeout(() => console.log("hello"), 0); requestAnimationFrame(() => console.log("tell me the next paint")); while (i <p>Here is the output on Chrome</p> <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172346056155999.gif?x-oss-process=image/resize,p_40" class="lazy" alt="You don"></p> <p>And here is the output in Firefox</p> <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172346056256543.gif?x-oss-process=image/resize,p_40" class="lazy" alt="You don"></p> <p>As you can see in the logs, when the browser in making changes in the UI, the requestAnimationFrame function will always have priority over other scheduled callbacks.</p> <p>Because on the web, we are constantly performing repaints, requestAnimationFrame is an obvious choice to implement timers.</p> <h2> Understanding the requestAnimationFrame function </h2> <p>The function only takes a callback as parameter. To provide context to the callback, it should take a timestamp indicating the time at which the previous frame has ended based on the time of the initial rendering of the page.</p> <p>The function will return an integer representing the request's identifier, this can be useful if you wish to cancel the request with the cancelAnimationFrame function.</p> <h2> A simple implementation of a Stopwatch in JavaScript </h2> <p>To implement a stopwatch, there are some requirements:</p>
- We should know after which amount of time it should tick (generally a second)
- We should know the delay of time after which the stopwatch should stop ticking
- The ticking intervals should be lesser than the delay
Taking all these requirements in considerations, the following code snippet will create a stopwatch for you
Outro
I know it might have been a long read but believe that you have enjoyed it. Anyway, if you have any questions or if you have any suggestion, feel free to reach me out.
Thank you for reading it and goodbye ?
The above is the detailed content of You dont need to set the time-out. For more information, please follow other related articles on the PHP Chinese website!

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Notepad++7.3.1
Easy-to-use and free code editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment