- 浏览: 1575931 次
- 性别:
- 来自: 北京
文章分类
最新评论
-
nich002:
原网站失效了。撸主简单粗暴的复制过来,可读性极差!差评!
Apache配置详解(最好的APACHE配置教程) -
107x:
不错,谢谢!
LINUX下查看文件夹下的文件个数! -
Hypereo:
好你妹,连个格式都没有!
Apache配置详解(最好的APACHE配置教程) -
resteater:
代码排版感觉有点乱!收发信息代码可读性不强!请问第一次发服务器 ...
java socket例子 -
resteater:
代码排版感觉有点乱!收发信息代码可读性不强!请问第一次发服务器 ...
java socket例子
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.
/* 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.
发表评论
-
几个不错的ff下调试插件
2009-12-11 11:14 1848记录一下经常使用的ff插件,其中firebug、switchh ... -
20 种提升网页速度的技巧
2009-04-15 20:19 1243From:http://www.ibm.com/develop ... -
25 个在 Web 中嵌入图表的免费资源
2009-04-14 21:27 1656From: http://www.cnbeta.com/art ... -
15个网站用户体验优化禁忌
2009-04-08 22:57 1167From:http://www.blueidea.com/de ... -
让IE8兼容IE7
2009-03-27 15:10 4175今天在搜狐首页发现:<meta http-equiv ... -
FF下分析页面加载的工具
2009-03-25 16:03 2465今天同事推荐YSlow作为 ... -
IE6下页面显示空白的问题
2009-03-24 17:01 5298今天又碰到了一个页面在IE6下加载完后一片空白的问题,而且页面 ... -
支持IE6、IE7的关闭页面的函数
2009-03-17 15:40 1692function closeWin() { var isI ... -
很弱很无奈的一段代码(打开的页面更新父窗口的链接)
2009-03-12 11:51 1012if(parent.window.opener) { pa ... -
js小脚本
2009-02-26 10:13 1538清除元素: var clearNode = functio ... -
处理一次性事件的模式
2009-02-12 20:20 1239有的时候我们需要给一个标签增加一次性的事件,比如先在输入框中增 ... -
Linux:rsync服务器的快速搭建和使用
2008-12-30 10:15 1318From: http://tech.ddvip.com/200 ... -
js导致的页面空白问题
2008-12-29 13:45 3127今天遇到一个很奇怪的问题,系统的一个页面在一台机器上无法完全展 ... -
IE6下history.back无效的问题
2008-12-26 23:56 3788解决IE6中history.back()无法返回的问题:< ... -
浏览器兼容比较好的设置min-width的方式
2008-12-12 18:45 2533<!DOCTYPE HTML PUBLIC " ... -
CSS代码分享:浏览器CSS Reset方法十例zz
2008-12-07 18:06 1152From: http://www.52css.com/arti ... -
在Javascript中,什么是闭包(Closure)
2008-12-02 11:11 1035from: http://javascript.chinaht ... -
Unicode、GB2312、GBK和GB18030中的汉字[转]
2008-11-25 15:22 3839From: http://blog.csdn.net/fmdd ... -
空字符串的split
2008-11-21 19:16 1556本来以为是零,但是在java和js里试了以后发现居然都是1,很 ... -
docType 相关的loose.dtd导致的无法获取scrollTop的解决
2008-11-19 11:32 1660function iecompattest(){ retu ...
相关推荐
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 ...
jQuery Timers 是一款专为 jQuery 设计的插件,它扩展了原生JavaScript中的setTimeout和setInterval函数,提供了更方便、更强大的定时器管理功能。这个插件的主要目的是简化在JavaScript和jQuery应用中处理定时任务...
**jQuery Timers 插件详解** 在Web开发中,JavaScript的时间管理和定时任务处理是不可或缺的部分。jQuery库,作为广泛使用的JavaScript库,虽然提供了基础的定时功能,但有时我们需要更高级和灵活的定时器管理。这...
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#中的定时器类,包括`System.Timers.Timer`和`System.Threading.Timer`,以及它们在实际应用...
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....
2. **初始化图片轮转**:在JavaScript中,首先定义要轮转的图片数组,然后使用timers插件设置轮转的逻辑。 ```javascript var images = ['image1.jpg', 'image2.jpg', 'image3.jpg']; var index = 0; var ...
jquery.timers-1.2.js 定时器插件
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 ...
Timers 有研究或探讨或开源的请加群:37424970 或联系本人MSN或邮箱:zhuseahui@yahoo.com.cn
《jQuery Timers 实现带暂停功能的全屏相册实例详解》 在Web开发中,全屏相册是一种常见的交互设计,它能够为用户提供沉浸式的浏览体验。在本实例中,我们将探讨如何利用jQuery Timers库来实现一个具有暂停功能的...
标题“实现数据库实时更新 jQuery Timers”涉及到的关键技术点主要包括jQuery库、定时器以及与数据库交互的基本原理。这里我们将深入探讨这些主题,并结合提供的文件名,解析如何利用jQuery的Timers扩展来实现实时...
本文实例讲述了C#中Forms.Timer、Timers.Timer、Threading.Timer的用法分析,分享给大家供大家参考。具体分析如下: 在.NET Framework里面提供了三种Timer ① System.Windows.Forms.Timer ② System.Timers.Timer ③...
"C_timers.rar_Timers_in_timers.rar"这个压缩包显然包含了关于如何在IBM PC上使用BIOS定时器的相关资料,主要文件是"C_timers.pdf"。下面我们将详细探讨BIOS定时器及其在编程中的应用。 BIOS(基本输入/输出系统)...
`jQuery Timers`插件的核心功能是提供了一种方式,使得JavaScript的计时器(如`setTimeout`和`setInterval`)在浏览器的后台模式下依然有效。这在处理需要实时更新内容的网页,如股票报价、聊天应用或者在线协作工具...
7. **计时器和倒计时(Timers and Countdowns)**:JavaScript的setInterval和setTimeout函数可用于创建计时器和倒计时,常用于促销活动或比赛报名。知识点包括时间格式化、日期对象和事件触发。 8. **滚动动画...
本教程将聚焦于"Spring Timers",讲解如何使用Spring来实现定时任务,这对于初学者掌握后台定时任务的处理至关重要。 首先,Spring 提供了两种主要的方式来执行定时任务:Spring的TaskExecutor接口和Spring ...
jQuery timers定时器简单易懂。。 直接调用,时间设置可以自己修改