【问题标题】:timeout function not working超时功能不起作用
【发布时间】:2017-05-06 02:28:50
【问题描述】:

我有以下代码,它应该检查是否加载了 jQuery,并避免在加载之前运行我的 jQuery 函数。

它似乎不起作用,我认为 Timeout 函数没有运行或通过它传递正确的函数(runwhenjqueryloaded)。

我在这方面花费的时间比客户的预算要多,因此非常感谢任何快速帮助。谢谢!

function runwhenjqueryloaded(){ 
  if (window.jQuery) {
    console.log("jquery rocks");
    //jquery exists, do what you want 
    $(function() {
      $('.flexslider').flexslider({
        animation: "slide",
        animationSpeed: 400,
        animationLoop: false,
        itemWidth: 210,
        itemMargin: 5,
        minItems: 1,
        maxItems: 4       
      });
    });

  } else {
    setTimeout(function() {runwhenjqueryloaded(); }, 60); 
  }
}
runwhenjqueryloaded();

【问题讨论】:

  • 嗯.. 很容易检查,不是吗。只需在传递给 setTimeout 的函数中添加另一个 console.log()。可能发生的是 jquery 实际上没有加载。另一方面,您是否以其他方式加载 jquery,然后使用 index.html 中的脚本标记?
  • 只需将 jQuery 脚本放在 HTML 中此脚本的上方即可。另外,您可以将setTimeout 称为setTimeout(runwhenjqueryloaded, 60)
  • 请注意setTimeout() 以毫秒为单位。因此,您将其设置为 60 毫秒。如果你想要秒,那就是 60000。

标签: javascript jquery timeout


【解决方案1】:
You can use setInterval instead.

function bootstrap($) {
    $(function() {
       $('.flexslider').flexslider({
           animation: "slide",
           animationSpeed: 400,
           animationLoop: false,
           itemWidth: 210,
           itemMargin: 5,
           minItems: 1,
           maxItems: 4       
       });
    });
}

var jqCheck = setInterval(function() {
   if (window.jQuery !== undefined) {
       bootstrap(window.jQuery);
       clearInterval(jqCheck);
   }
}, 60);

【讨论】:

  • 这工作得很好......除了现在我需要一种方法来加载 jQuery,如果它没有加载(这被集成在第 3 方平台中,并且由于某种原因它并不总是加载 jQuery ...)。我想我理解你对 setInterval 函数做了什么——你将 flexslider 包装在 bootstrap 函数中,然后检查 jQuery,这样引导程序不会运行,除非 window.jQuery 返回 true,对吗?那么在该代码中的哪一点,我将添加代码以现在强制加载 jQuery,然后再次运行该检查?非常感谢!
【解决方案2】:

setTimeout 在您的代码中运行良好,但您可以更简单地编写它:

setTimeout(runwhenjqueryloaded,60)

你不是在其他地方有错误吗? 尝试调试或在 runwhenjqueryloaded() 的开头放置一个 console.log 并在 "else" 之后放置另一个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 2016-08-09
    • 2021-03-27
    • 2019-04-08
    • 1970-01-01
    • 2012-11-29
    • 2011-11-03
    • 1970-01-01
    相关资源
    最近更新 更多