首页 > 网站 > 建站经验 > 正文

JS中的sleep操作

2024-04-25 20:31:17
字体:
来源:转载
供稿:网友

 今天有个程序员朋友问起我在js中实现sleep休眠一段时间怎样操作的问题,我整理了可以实现js中自定义方法实现停留几秒sleep的方法,希望可以帮助到需要的朋友

首先声明,js中是不自带sleep方法的,因此要想实现休眠必须自定义代码,下面是我从网上找到的最常见的写法,这写法思路是比较简单易懂的循环写法,但是这个方法的缺点在于它,其实并没有让脚本解释器sleep下来,而且有让CPU迅速上到高负荷的附作用。浏览器甚至会在该段时间内处于假死状态。

function sleep(numberMillis) {

var now = new Date();

var exitTime = now.getTime() + numberMillis;

while (true) {

now = new Date();

if (now.getTime() > exitTime)

return;

}

}

最后,给大家推荐一套实用的写法:

var $break = new Object();

var $continue = new Object();

var Enumerable = {

each: function(iterator) {

var index = 0;

try {

this._each(function(value) {

try {

iterator(value, index++);

} catch (e) {

if (e != $continue) throw e;

}

});

} catch (e) {

if (e != $break) throw e;}

},

all: function(iterator) {

var result = true;

this.each(function(value, index) {

result = result && !!(iterator || Prototype.K)(value, index);

if (!result) throw $break;

});

return result;

},

any: function(iterator) {

var result = true;

this.each(function(value, index) {

if (result = !!(iterator || Prototype.K)(value, index))

throw $break;

});

return result;

},

 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表