Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement JavaScript timer in browser

2025-01-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to implement JavaScript timer in browsers. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Using infinite synchronization loops in Web Worker

Because Web Worker is essentially a Web thread, you can loop through it indefinitely without blocking the main thread. This gives you access to microsecond time resolution. This is particularly useful for making time-critical decisions in Worker, allowing the main thread to know exactly when is appropriate. For example, render something as long as microseconds are prime. To access microseconds, you can use performance.now.

Advantages

Microsecond resolution.

The cost of UI threads is almost zero.

Using Web Workers's message passing design, it is completely asynchronous from the point of view of UI threads.

It ends safely and, unlike setInterval, calls worker.terminate to guarantee that no more messages will be received.

Quote MDN: "the Terminate () method of Worker immediately terminates Worker. It will not wait for Worker to finish the program, but will stop immediately."

Shortcoming

Even if you can make millisecond decisions, the message that returns the UI thread is asynchronous. You can't render in time like you make a decision in Worker.

Keep the thread fully occupied. The cell phone battery may get better soon.

Web Worker support is required.

The tab is not paused when it is not in focus.

Use CSS animation to handle time events (animationiteration)

If you create a div with infinite animation. You can subscribe to its animationiteration event and be notified when the event animation-duration is called back.

Advantages

When automatically paused, the label is not in focus. When the tag is not in focus, the event is not triggered at all. There is no need to worry about getting stuck in the calls, which will run as soon as the tabs are displayed again.

When you delete a hidden div from DOM, it cleans up automatically. For example, if you have a React component that renders time, you don't need to do anything during uninstallation. The div will be deleted and the event will no longer be triggered.

The calling logic is elegant: .addEventListener ("animationiteration", fun).

A super clean way to delay starting the timer: animation-delay.

Shortcoming

It's a little too smart and may confuse your collaborators.

Depends on DOM and CSSOM. Other CSS rules may interfere with your rules. That's why I suggest creating an arbitrary nonexistent tag like this.

. Maybe use CSS animation code to neatly put it into it to create custom elements?

If the element has a display: none; attribute, it is invalid.

Use SVG tags (SMIL animation)

If you call animate.addEventListener ('repeat', fun) like this, your function will be called once a second.

Advantages

It takes effect even if the SVG is display: none;.

Automatically stops when the SVG is deleted from the DOM.

Rendering does not begin until the full page is loaded.

Automatically pauses when the tab is in focus.

Shortcoming

It's a little too smart and may confuse your collaborators.

Depends on DOM and CSSOM. The same warning as above. Other CSS rules may interfere with your configuration.

IE and Edge (before Chromium) are not supported.

Inaccurate according to my test, it may delay 15ms.

It doesn't start until the full page loads. Yes, it may be a disadvantage, but it is also a function.

Use Web Animations API

Web Animations API allows you to animate DOM elements in JavaScript.

Interestingly, you can animate unrendered elements! This allows you to access the timing mechanism in pure JS (and Web api).

This is an alternative implementation of setTimeout:

Function ownSetTimeout (callback, duration) {const div = document.createElement ('div'); const keyframes = new KeyframeEffect (div, [], {duration, iterations: 1}); const animation = new Animation (keyframes, document.timeline); animation.play (); animation.addEventListener (' finish', () = > {callback ();});}

It's neat, isn't it?

Advantages

No DOM interaction is required.

People who are not familiar with it are easy to understand.

Automatically pauses when the label is not in focus.

Shortcoming

It's still a suggestion. Do not use it in production.

Terrible compatibility. May only apply to Chromium.

It's still a little counterintuitive.

Pause when the label is not in focus. It can be bad if it is used as a substitute for setTimeout.

Cannot be used at intervals. Only onfinish activities are available.

Inaccurate according to my test, error 5ms.

This is the end of the article on "how to implement JavaScript timer in browser". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report