`
liudaoru
  • 浏览: 1579218 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

How JavaScript Timers Work[z]

    博客分类:
  • Ajax
阅读更多

From: http://ejohn.org/blog/how-javascript-timers-work/

 

At a fundamental level it's important to understand how JavaScript timers work. Often times they behave unintuitively because of the single thread which they are in. Let's start by examining the three functions to which we have access that can construct and manipulate timers.

  • var id = setTimeout(fn, delay); - Initiates a single timer which will call the specified function after the delay. The function returns a unique ID with which the timer can be canceled at a later time.
  • var id = setInterval(fn, delay); - Similar to setTimeout but continually calls the function (with a delay every time) until it is canceled.
  • clearInterval(id);, clearTimeout(id); - Accepts a timer ID (returned by either of the aforementioned functions) and stops the timer callback from occurring.

In order to understand how the timers work internally there's one important concept that needs to be explored: timer delay is not guaranteed. Since all JavaScript in a browser executes on a single thread asynchronous events (such as mouse clicks and timers) are only run when there's been an opening in the execution. This is best demonstrated with a diagram, like in the following:


(Click to view full size diagram)

 

There's a lot of information in this figure to digest but understanding it completely will give you a better realization of how asynchronous JavaScript execution works. This diagram is one dimensional: vertically we have the (wall clock) time, in milliseconds. The blue boxes represent portions of JavaScript being executed. For example the first block of JavaScript executes for approximately 18ms, the mouse click block for approximately 11ms, and so on.

Since JavaScript can only ever execute one piece of code at a time (due to its single-threaded nature) each of these blocks of code are "blocking" the progress of other asynchronous events. This means that when an asynchronous event occurs (like a mouse click, a timer firing, or an XMLHttpRequest completing) it gets queued up to be executed later (how this queueing actually occurs surely varies from browser-to-browser, so consider this to be a simplification).

To start with, within the first block of JavaScript, two timers are initiated: a 10ms setTimeout and a 10ms setInterval. Due to where and when the timer was started it actually fires before we actually complete the first block of code. Note, however, that it does not execute immediately (it is incapable of doing that, because of the threading). Instead that delayed function is queued in order to be executed at the next available moment.

Additionally, within this first JavaScript block we see a mouse click occur. The JavaScript callbacks associated with this asynchronous event (we never know when a user may perform an action, thus it's consider to be asynchronous) are unable to be executed immediately thus, like the initial timer, it is queued to be executed later.

After the initial block of JavaScript finishes executing the browser immediately asks the question: What is waiting to be executed? In this case both a mouse click handler and a timer callback are waiting. The browser then picks one (the mouse click callback) and executes it immediately. The timer will wait until the next possible time, in order to execute.

Note that while mouse click handler is executing the first interval callback executes. As with the timer its handler is queued for later execution. However, note that when the interval is fired again (when the timer handler is executing) this time that handler execution is dropped. If you were to queue up all interval callbacks when a large block of code is executing the result would be a bunch of intervals executing with no delay between them, upon completion. Instead browsers tend to simply wait until no more interval handlers are queued (for the interval in question) before queuing more.

We can, in fact, see that this is the case when a third interval callback fires while the interval, itself, is executing. This shows us an important fact: Intervals don't care about what is currently executing, they will queue indiscriminately, even if it means that the time between callbacks will be sacrificed.

Finally, after the second interval callback is finished executing, we can see that there's nothing left for the JavaScript engine to execute. This means that the browser now waits for a new asynchronous event to occur. We get this at the 50ms mark when the interval fires again. This time, however, there is nothing blocking its execution, so it fires immediately.

Let's take a look at an example to better illustrate the differences between setTimeout and setInterval.

  setTimeout(function(){
    /* Some long block of code... */
    setTimeout(arguments.callee, 10);
  }, 10);
 
  setInterval(function(){
    /* Some long block of code... */
  }, 10);

These two pieces of code may appear to be functionally equivalent, at first glance, but they are not. Notably the setTimeout code will always have at least a 10ms delay after the previous callback execution (it may end up being more, but never less) whereas the setInterval will attempt to execute a callback every 10ms regardless of when the last callback was executed.

There's a lot that we've learned here, let's recap:

  • JavaScript engines only have a single thread, forcing asynchronous events to queue waiting for execution.
  • setTimeout and setInterval are fundamentally different in how they execute asynchronous code.
  • If a timer is blocked from immediately executing it will be delayed until the next possible point of execution (which will be longer than the desired delay).
  • Intervals may execute back-to-back with no delay if they take long enough to execute (longer than the specified delay).

All of this is incredibly important knowledge to build off of. Knowing how a JavaScript engine works, especially with the large number of asynchronous events that typically occur, makes for a great foundation when building an advanced piece of application code.

分享到:
评论

相关推荐

    A Stock Exchange simulator to show how timers and randon num

    A Stock Exchange simulator to show how timers and randon number generators work together. A cool simulation for anyone who might think about playing the stocks and spending money and get a general ...

    jQueryTimers

    jQuery Timers 是一款专为 jQuery 设计的插件,它扩展了原生JavaScript中的setTimeout和setInterval函数,提供了更方便、更强大的定时器管理功能。这个插件的主要目的是简化在JavaScript和jQuery应用中处理定时任务...

    jquery.timers.js

    **jQuery Timers 插件详解** 在Web开发中,JavaScript的时间管理和定时任务处理是不可或缺的部分。jQuery库,作为广泛使用的JavaScript库,虽然提供了基础的定时功能,但有时我们需要更高级和灵活的定时器管理。这...

    Beginning.JavaScript.5th.Edition

    Title: Beginning ...Beginning JavaScript, 5th Edition shows you how to work effectively with JavaScript frameworks, functions, and modern browsers, and teaches more effective coding practices using ...

    c# Timers简单的定时应用

    在C#编程中,`Timers` 是一个非常重要的组件,它允许程序员创建定期执行的任务,无需显式地轮询时间。本篇文章将深入探讨C#中的定时器类,包括`System.Timers.Timer`和`System.Threading.Timer`,以及它们在实际应用...

    commonj系列包

    commonj.work.Work.java commonj.work.WorkCompletedException.java commonj.work.WorkEvent.java commonj.work.WorkException.java commonj.work.WorkItem.java commonj.work.WorkListener.java commonj.work....

    Jquery+timers插件实现图片轮转

    2. **初始化图片轮转**:在JavaScript中,首先定义要轮转的图片数组,然后使用timers插件设置轮转的逻辑。 ```javascript var images = ['image1.jpg', 'image2.jpg', 'image3.jpg']; var index = 0; var ...

    Mastering.JavaScript.High.Performance.1784397296

    Test existing JavaScript code using JSLint and understand how to better optimize JavaScript code Create your own build system for JavaScript projects using Node.js and GulpJS Get to know best ...

    jquery.timers-1.2.js

    jquery.timers-1.2.js 定时器插件

    Timers 定时器

    Timers 有研究或探讨或开源的请加群:37424970 或联系本人MSN或邮箱:zhuseahui@yahoo.com.cn

    jquery_timers实现带暂停功能的全屏相册实例源码

    《jQuery Timers 实现带暂停功能的全屏相册实例详解》 在Web开发中,全屏相册是一种常见的交互设计,它能够为用户提供沉浸式的浏览体验。在本实例中,我们将探讨如何利用jQuery Timers库来实现一个具有暂停功能的...

    实现数据库实时更新 jQuery Timers

    标题“实现数据库实时更新 jQuery Timers”涉及到的关键技术点主要包括jQuery库、定时器以及与数据库交互的基本原理。这里我们将深入探讨这些主题,并结合提供的文件名,解析如何利用jQuery的Timers扩展来实现实时...

    C#中Forms.Timer、Timers.Timer、Threading.Timer的用法分析

    本文实例讲述了C#中Forms.Timer、Timers.Timer、Threading.Timer的用法分析,分享给大家供大家参考。具体分析如下: 在.NET Framework里面提供了三种Timer ① System.Windows.Forms.Timer ② System.Timers.Timer ③...

    C_timers.rar_Timers_in_timers.rar

    "C_timers.rar_Timers_in_timers.rar"这个压缩包显然包含了关于如何在IBM PC上使用BIOS定时器的相关资料,主要文件是"C_timers.pdf"。下面我们将详细探讨BIOS定时器及其在编程中的应用。 BIOS(基本输入/输出系统)...

    jquery网页静止自动执行jquery.timers

    `jQuery Timers`插件的核心功能是提供了一种方式,使得JavaScript的计时器(如`setTimeout`和`setInterval`)在浏览器的后台模式下依然有效。这在处理需要实时更新内容的网页,如股票报价、聊天应用或者在线协作工具...

    JavaScript精彩网页特效实例精粹

    7. **计时器和倒计时(Timers and Countdowns)**:JavaScript的setInterval和setTimeout函数可用于创建计时器和倒计时,常用于促销活动或比赛报名。知识点包括时间格式化、日期对象和事件触发。 8. **滚动动画...

    Spring Timers

    本教程将聚焦于"Spring Timers",讲解如何使用Spring来实现定时任务,这对于初学者掌握后台定时任务的处理至关重要。 首先,Spring 提供了两种主要的方式来执行定时任务:Spring的TaskExecutor接口和Spring ...

    jQuery timers定时器

    jQuery timers定时器简单易懂。。 直接调用,时间设置可以自己修改

Global site tag (gtag.js) - Google Analytics