延迟后运行功能


77

我存储了以下全局jQuery函数,但是在页面加载时,我想在1000个延迟后执行它。我的语法有问题吗?我知道延迟总是在功能之前发生。它没有响应。

全局功能:

function showpanel() {     
       $(".navigation").hide();
       $(".page").children(".panel").fadeIn(1000);
    ;}

执行功能:

parallax.about.onload=function(){
    $('#about').delay(3000).showpanel();
};

这就是您正在寻找的人:)希望对您有所帮助,stackoverflow.com
questions/5322344/…

第一个明确的问题是您试图将showpanel作为另一个对象的方法来调用(在这种情况下,这是由delay()调用返回的jQuery对象)。但是您已经将showpanel声明为一个简单,可直接访问的函数,而不是任何对象的方法。JavaScript无法以这种方式工作。
BobS 2012年

Answers:


146
$(document).ready(function() {

  // place this within dom ready function
  function showpanel() {     
    $(".navigation").hide();
    $(".page").children(".panel").fadeIn(1000);
 }

 // use setTimeout() to execute
 setTimeout(showpanel, 1000)

});

更多信息请看这里


47

我搜索后发现以下URL中的解决方案更好

http://www.tutorialrepublic.com/faq/call-a-function-after-some-time-in-jquery.php

值得尝试。

它将给定功能添加到要在当前为this的匹配元素上执行的功能队列中。

 $(this).delay(1000).queue(function() {

     // your Code | Function here
     
     $(this).dequeue();
  
  });

然后在队列中为匹配的元素执行下一个功能,又是当前的功能。

-编辑[出命令的可能解释]

看一下命令

我们命令jQuery引擎在内部队列中添加一个函数,然后在指定的时间后,我们命令它调用该函数,但是到目前为止,我们从未告诉过它要从引擎中退出。对?!然后,在完成所有操作后,我们将其从jQuery引擎中手动出队。我希望解释能有所帮助。


您能否总结一下解决方案并解释其工作原理?仅链接到解决方案并不理想,因为该链接将来可能会在某个时候停止工作……
devlin carnate

@devlincarnate我更新了这篇文章。阅读它,看看它是否容易理解。希望它有用。
ebrahim.mr 2016年

4
这不能解释什么队列可以做什么或为什么需要出队。使服务器出队的目的是什么?我不希望函数执行一次以上,那么为什么要使它出队呢?
Triynko '16

$('#main > ul').delay(100).queue(function () { $(this).attr('data-uk-grid', 'masonry: true; parallax: 150;').dequeue() }); $('#main > ul').delay(1).queue(function () { $(this).removeClass('uk-grid uk-flex-top uk-flex-wrap-top').dequeue() });
奥利维尔(Olivier)

1
@Niklas我更新了帖子。请看看。
ebrahim.mr

30

您可以在jQuery中添加超时功能(3秒后显示警报):

$(document).ready(function($) {
    setTimeout(function() {
     alert("Hello");
    }, 3000);
});

1

该答案仅对了解如何使用JQuery函数进行延迟很有用delay

假设您有一个警报,并且想要设置警报文本,然后显示该警报,并在几秒钟后将其隐藏。

这是简单的解决方案:

$(".alert-element").html("I'm the alert text").fadeIn(500).delay(5000).fadeOut(1000);

这是完全简单的:

  1. .html() 将更改 .alert-element
  2. .fadeIn(500) 将在500毫秒后消失
  3. jQuerydelay(5000)函数将在调用下一个函数之前产生5000毫秒的延迟
  4. .fadeOut(1000) 声明的末尾将淡出 .alert-element
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.