【问题标题】:jQuery how to make event occur every x seconds?jQuery如何让事件每x秒发生一次?
【发布时间】:2010-09-25 00:23:44
【问题描述】:
$("#clickMe").click(                                    
     function(){   
          if (i == 1) {            
               i = i+1
               $("#div p").css("left", "-" + width * i + "px");  
            }
});

正如您所见,当有人单击按钮时 -margin 会发生变化。如果我希望它每 10 秒在站点加载时发生一次怎么办?

谢谢。

【问题讨论】:

    标签: javascript jquery timer


    【解决方案1】:

    使用setInterval 设置定时事件:

    setInterval(
         function(){   
              if (i == 1) {            
                   i = i+1
                   $("#div p").css("left", "-" + width * i + "px");  
                }
         },
         10000  /* 10000 ms = 10 sec */
    );
    

    【讨论】:

    • setInterval() 分配给一个变量,因此您可以根据需要使用clearInterval() 停止它。 ==> var timer = setInterval( ... );,然后停止:clearInterval(timer);
    【解决方案2】:

    使用setInterval 函数。

    【讨论】:

      【解决方案3】:
      var cancel_margin_change = false;
      $(function() {
      
         var i = 1, width = 10, xtime = 10000,
            margin_change = function() {
      
                if (i == 1)
                   $("#div p").css("left", "-" + (width * (++i)) + "px");
      
                if (!cancel_margin_change)
                   setTimeout(margin_change, xtime);
             };
      
         margin_change();  
      
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-04-30
        • 1970-01-01
        • 1970-01-01
        • 2013-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多