开发者

timing/waiting in jQuery

I am writting a banner rotator and I want it to cycle among few pictures after few seconds. Does jQuery has something for waiting and then calling the callback? I can see the .delay method, but it doesn't seem to have开发者_运维百科 a callback function. Or maybe I should use a browser-dependant function? Or maybe javascript already contains a function that I need? I am new to javascript :-| .


You can always use the native javascript:

setTimeout(function(){ /* do your stuff */ }, 1000);

You can have some fun with mixins:

var timeoutCallback = function() {
    this.foo = 5;
}

var scheduleTimeout = function(obj, delay) {
    setTimeout(function(){ timeoutCallback.call(obj); }, delay);
}

var myobj = { foo: 1, bar: 2 }
scheduleTimeout(myobj, 1000); // myobj.foo becomes 5 after 1000ms delay


You are right about delay being the way to go, if what you wish to do is time jQuery effects.

Look at the jQuery documentation on effects, and pay close attention to how the effects queue work, it's a very nice framework. :)


So you need to start your effect not immediately, but after some time? So right, this is delay() function.

$("#test").delay(3000).fadeOut('slow');
// after 3 seconds element starts to fade out

P.S.

But be carefully with delay. For example this code:

$("#test").fadeOut(1000).sleep(1000).fadeIn(1000);

won't work like somebody may think. Sleep will run synchronous with fadeOut but not after it terminates. So If you want to make an effect complete and than make something - you should make by Callback function.


This is the simplest example I can think of and a condensed version of what Joy Dutta already said. It first shows "Please wait" and after 3 seconds "...done!". Throw it into the Firebug console and see what happens :-)

$('body').html('Please wait!');
setTimeout(function (){$('body').html('...done!');}, 3000);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜