2013-11-14 142 views
0

我正在使用jQuery,然后按顺序加载我的脚本。然而,服务器CPU上的即时轰击仍然太高。我曾尝试加入.delay像这样的。那么之后:Jquery:然后添加延迟

siteVisits() 
    .then(siteTerms) 
    .delay(30000) 
    .then(siteSources) 
    .delay(30000) 
    .then(siteBrowsers) 
    .delay(30000) 
    .then(siteCountries) 
    .delay(30000) 
    .then(siteContent); 

但是我得到这个错误:

Uncaught TypeError: Object #<Object> has no method 'delay' 

有没有人有我如何可以将每个功能之前的延迟任何想法叫?

在此先感谢

+2

延迟只适用于动画。你不能在任何地方使用它。我很好奇,看看这是怎么回事,因为将延迟(setTimeout)引入以这种方式链接的函数是很困难的。 – Archer

+0

我从错误中收集了这些信息,当我说'如何在每个函数被调用之前添加延迟'我的意思是任何人都有任何想法如何实现这个另一种方式? – MarkP

+0

我会研究那些对服务器来说过于密集的功能,并优化它们。等待2分钟让页面完全加载(因为如果代码工作,您的代码将完成)不是一个可接受的解决方案。 –

回答

0

这不像.delay的行为,应使用只能延缓动画,对于这种˚F延迟,你将不得不使用的setTimeout();

siteVisits() 
    .then(function() { 
     setTimeout(function() { 
      siteTerms.then(function() { 
       setTimeout(function() { 
        siteTerms.then() 
       }, 30000); 
      }) 
     }, 30000); 
    }); 

但是为什么这么拖延?

0

这里使用延迟是错误的,它们是为完全不同的问题而创建的。不要因为你喜欢花哨的语法而拖延他们。

function DelayedExecutor(delay) { 
    var self = this, queue = [], id; 

    function runNext() { 
     var def = queue.shift(); 
     if (def && typeof def.func === "function") { 
      def.func.apply(def.context, def.args); 
     } 
     if (queue.length === 0) { 
      id = clearInterval(id); 
     } 
    } 

    this.add = function (func, args, context) { 
     queue.push({func: func, args: args, context: context}); 
     if (!id) { 
      id = setInterval(runNext, delay); 
      runNext(); 
     } 
     return self; 
    }; 
} 

var de = new DelayedExecutor(30000); /* new and improved model! */ 
de.add(siteTerms /*, [arguments], thisArg */); 
de.add(siteSources); 
de.add(siteBrowsers).add(siteCountries).add(siteContent);