1

我正在创建一个函数,我可以在其中执行一些 jquery 代码......然后暂停说...... 5 秒,然后执行其他东西..

像这样的东西:

function myFunc() {
    var str1 = 'This is the starting text';
        var str2 = 'This is the ending text';
          $("#label").html(str1);

        //I need a pause here (5000 ms) ---

          $("#label").html(str2);

}

我怎样才能在那里停下来?

4

5 回答 5

5

这可以使用 jQuery 的queue方法按顺序完成

jQuery方式:

$('#label')
    .queue(function (n) {
        ...your code here...
        n(); //dequeue the next item in the queue
    })
    .delay(5000)
    .queue(function (n) {
        ...your second bit of code here...
        n(); //dequeue the next item in the queue
    });

虽然了解如何使用setTimeout也很好。

这样做的好处queue是它默认与fx队列一起工作,尽管您可以选择指定不同的队列名称。

非jQuery方式:

function first() {
    ...your code here...
    setTimeout(second, 5000);
}
function second() {
    ...your second bit of code here...
}
first();
于 2012-09-11T14:00:47.017 回答
4

您可以使用超时来处理您的暂停

function myFunc() {
    var str1 = 'This is the starting text';
        var str2 = 'This is the ending text';
          $("#label").html(str1);
          var plzwait=setTimeout(function(){  $("#label").html(str2);  }, 5000);
于 2012-09-11T13:59:38.213 回答
2

不确定您要完成什么,但您可能不应该尝试使其同步并暂停它,这会冻结应用程序。相反,我建议您使用超时,在给定的时间后执行您想要的代码。

function myFunc() {
    var str1 = 'This is the starting text';
        var str2 = 'This is the ending text';
          $("#label").html(str1);

          setTimeout(function() { 
             // Do what you want to do after a certain time in here 
             $("#label").html(str2); 
          }, 5000);

}
于 2012-09-11T13:59:39.027 回答
1

jQuery 有delay( ),它接受毫秒并与效果一起工作。

这是一个在文本更改以引起注意时淡入的示例。

var str1 = "I am the first string";
var str2 = "This is the second string!";
var label = $("#label")
    label.html(str1).delay(5000).fadeOut("fast",function(){label.html(str2)}).fadeIn("slow");

jsFiddle 示例

于 2012-09-11T13:59:50.293 回答
1

采用setTimeout();

function myFunc() {
    var str1 = 'This is the starting text';
        var str2 = 'This is the ending text';
          $("#label").html(str1);

        //I need a pause here (5000 ms) ---
        setTimeout(function(){
         $("#label").html(str2);
        },5000);


}
于 2012-09-11T14:00:03.487 回答