1

在想出下面的函数之后,我的下一个任务是让它每 3 秒循环一次。

  Chat.fetch(function(x) // x is an array delivered by .fetch
    {
      for (var i = 0; i<x.length; i++)
        {
          Chat.display(x[i]); // and .display only takes strings as an argument
        }
    });

现在我的第一个初学者的想法是以某种方式将上述所有内容放入一个变量中。

var myvariable = Chat.fetch(etc...

然后我会做类似的事情

setInterval(myvariable, 3000);

显然那没有用。阻止这种方法的功能是什么?

4

1 回答 1

1

我会提出一个不同的解决方案。

// define the callback function
var displayMessages = function(x) // x is an array delivered by .fetch
    {
      for (var i = 0; i<x.length; i++)
        {
          Chat.display(x[i]); // and .display only takes strings as an argument
        }
      // Ivoke Chat.fetch with this callback again after 3 seconds
      setTimeout( function(){ Chat.fetch( displayMessages ); }, 3000 );
    } 
// start polling
Chat.fetch( displayMessages );

现在,每次调用回调时,它都会Chat.fetch在之前的消息呈现后 3 秒后再次触发。

于 2013-09-26T08:12:54.963 回答