草庐IT

javascript - setTimeOut() 或 setInterval() 。 4 种方法来应用相同的东西。哪个最好?

coder 2025-02-14 原文

我正在显示关于给定结束时间的倒计时 watch 。

虽然它工作完美,但我想知道哪种是最好的应用方法。

下面是我的倒计时功能。

  var timerId;
  var postData = {endDate : endDate, tz : tz};  
  var countdown = function()
    { 
      $.ajax({
               type : 'post',
               async : false,
               timeout : 1000,
               url : './ajax_countdown.php',
               data : $.param(postData),
               dataType : 'json',
               success : function (resp){
                  $('#currentTime').html(resp.remainingTime);
               }
            }); 
     }

我想要的是函数(倒计时)应该每 1 秒后自动调用,如果它没有在 1 秒内执行/完成,则取消当前的 ajax 并开始新的 ajax 调用。

现在我发现有4种工作方式

方法 1:使用 setInterval() 和 window 对象

window.setInterval(countdown, 1000);

方法二:独立使用setInterval()

setInterval(function() {countdown()}, 1000);

方法3:在函数内部使用setTimeOut调用其他函数来初始化主函数

var countdown = function() { 
     $.ajax({ //ajax code });
     timerId = setTimeout(countdown, 5000); // assign to a variable
 }

function clockStart() {  
        if (timerId) return
        countdown();
}
clockStart(); // calling this function 

方法四:使用匿名函数调用

var countdown = function() { 
     $.ajax({ //ajax code });
     timerId = setTimeout(countdown, 5000);
 }
  (function(){
         if (timerId) return;
         countdown();
})();

请告诉我

  • 每种方法的优缺点是什么?哪种方法最好/正确?
  • 我应该使用 clearTimeOut() 还是 clearInterval()

引用资料

http://javascript.info/tutorial/settimeout-setinterval

Calling a function every 60 seconds

http://www.electrictoolbox.com/using-settimeout-javascript/

最佳答案

我不会使用您的任何方法。原因是setTimeoutsetInterval do not guarantee that your code will execute after the specified delay .这是因为 JavaScript 是单线程的。

如果我需要在指定的延迟后只调用一次函数,那么我使用 setTimeout。但是,如果我需要在固定时间间隔后调用一个函数,那么我不会使用 setInterval。相反,我使用 delta timing .这是 code .

使用增量计时的优点是您的代码将执行更接近您指定的固定时间间隔。它会 self 纠正。创建和使用增量计时器很简单。比如你的代码会这样写:

var timer = new DeltaTimer(function (time) {
    $.ajax({
        // properties
    });

    if (time - start >= 5000) timer.stop();
}, 1000);

var start = timer.start();

上面的 delta timer 比 setInterval(方法 1)更好,利用了 setTimeout(方法 2)但也 self 纠正,使用函数启动定时器(方法 3),并且不会用特殊的 clockStart 函数(方法 4)污染作用域。

此外,您可以在计时器启动后轻松获得调用函数的确切时间,因为调用函数的时间作为参数传递给函数。计时器还有一个 stop 方法来停止计时器。要再次启动它,请再次调用 start

编辑:

如果你想让 DeltaTimer 看起来更像 setInterval(自动启动计时器),你可以按如下方式实现一个 spawn 函数:

DeltaTimer.spawn = function (render, interval) {
    var timer = new DeltaTimer(render, interval);

    var start = timer.start = function (start) {
        return function () {
            render.start = start();
        };
    }(timer.start);

    start();

    return timer;
};

然后您可以自动创建并启动 DeltaTimer,如下所示:

var timer = DeltaTimer.spawn(function countdown(time) {
    $.ajax({
        // properties
    });

    if (time - countdown.start >= 5000) timer.stop();
}, 1000);

因此 var timer = DeltaTimer.spawn(funct, delay); 等同于 var interval = setInterval(funct, delay);timer.stop (); 等同于 clearInterval(interval);。我想这就是您可以实现自动化的最大程度了。

关于javascript - setTimeOut() 或 setInterval() 。 4 种方法来应用相同的东西。哪个最好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11520834/

有关javascript - setTimeOut() 或 setInterval() 。 4 种方法来应用相同的东西。哪个最好?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  5. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  6. Ruby 方法() 方法 - 2

    我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby​​-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco

  7. ruby - 难道Lua没有和Ruby的method_missing相媲美的东西吗? - 2

    我好像记得Lua有类似Ruby的method_missing的东西。还是我记错了? 最佳答案 表的metatable的__index和__newindex可以用于与Ruby的method_missing相同的效果。 关于ruby-难道Lua没有和Ruby的method_missing相媲美的东西吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/7732154/

  8. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  9. ruby-on-rails - Rails 应用程序之间的通信 - 2

    我构建了两个需要相互通信和发送文件的Rails应用程序。例如,一个Rails应用程序会发送请求以查看其他应用程序数据库中的表。然后另一个应用程序将呈现该表的json并将其发回。我还希望一个应用程序将存储在其公共(public)目录中的文本文件发送到另一个应用程序的公共(public)目录。我从来没有做过这样的事情,所以我什至不知道从哪里开始。任何帮助,将不胜感激。谢谢! 最佳答案 无论Rails是什么,几乎所有Web应用程序都有您的要求,大多数现代Web应用程序都需要相互通信。但是有一个小小的理解需要你坚持下去,网站不应直接访问彼此

  10. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

随机推荐