javascript之setTimeout使用详解

原创文章,转载请注明: 转载自庆亮的博客-webgame架构

本文链接地址: javascript之setTimeout使用详解

setTimeout的第一个参数为函数名或者以""包含的js代码如果是第一种情形当函数带有参数时往往不能达到我们预期需要的效果文字说明比较抽象我们来看代码:

function test(){

alert(‘A’);

}

setTimeout(test, 1000); //正常, 1秒后执行

b="Hello";

function test2(a){

alert(a);

}

setTimeout("test2(b)", 1000);//正常, 1秒后执行

c="world";

function test3(a){

alert(a);

}

setTimeout(test3(c), 1000); //立刻执行, 并没有延迟

d="haha";

function test(d){

return function()

{

alert(a);

}

}

setTimeout(test(d), 1000);//正常, 1秒后执行

prototype.js中也有类似的应用

Function.prototype.bind = function(object){

__method = this;

return function() {

__method.apply(object, arguments);

}

}

function Test() {}

Test.prototype.start  = function(){

setTimeout(this.run.bind(this), 1000);

}

Test.prototype.run = function(){

alert(‘A’);

this.runNext();

}

Test.prototype.runNext = function(){

setTimeout(this.run.bind(this), 2000);

}

test = new Test();

test.start();

这样在客户端就可以循环的向服务器请求信息了(如聊天室).

Leave a comment

0 Comments.

Leave a Reply

You must be logged in to post a comment.