【问题标题】:timeout not working as expected超时未按预期工作
【发布时间】:2017-04-23 06:21:35
【问题描述】:

我正在尝试让按钮从默认的“这将更改”更改为“新消息”,然后每 2 秒更改为“someButton”,然后单击停止。

到目前为止,我有这个代码:

var timeouts = [];

var someArray = {button: 'new Message', button: 'Some Btn'};

$(document).ready(function(){
var i = 2000;
$.each(someArray, function(index, value){
    timeouts.push(setTimeout(function(){
          $(index).html(value);
     },i));
     i = i + 2000;
});


$('#stop').click(function(){
    $.each(timeouts, function (_, id) {
       clearTimeout(id);
    });
    timeouts = [];
    $(button).html('Some Btn');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type='button'>
This will change
</button>
<a id='stop' href='#'>Stop</a>

似乎忽略了第一个setTimeout(),或者新消息索引上没有运行超时。然后当我按下点击按钮时,没有超时被清除?

如果我出错了,我们将不胜感激。

更新:我想让它尽可能地面向 jQuery,谢谢!

【问题讨论】:

  • 使用 setInterval 而不是没有“超时”数组。
  • 如何清除间隔?我正在尝试坚持使用 JQuery 来做到这一点,@ryanlutgen
  • var myinterval = setInterval(function() { }); clearInterval(myinterval)
  • 首先,您的someArray 不是数组。它是一个对象
  • kdot,请在问题正文中提及您的所有疑问或问题。和@ryanlutgen,最好你发布答案,这样你就可以获得奖励。

标签: javascript jquery html timeout


【解决方案1】:

您的用例准确地描述了 setInterval 的用途。

“重复调用一个函数或执行一段代码sn-p,每次调用之间有固定的时间延迟。返回一个intervalID。”

setInterval 函数返回一个 ID,可以将其传递给 clearInterval 以阻止代码每 X 秒执行一次。

我已经发布了一个代码 sn-p 来说明我认为你想要实现的目标。

Plnkr Link

var strings = ["This will change", "Some button"];
var intervalID;
var button;
var index = 0;

$(document).ready(function() {
  button = $("#myButton");
  intervalID = window.setInterval(function() {
    console.log("hi");
    button.html(strings[index]);
    index = (index == 1 ? 0 : 1);
  }, 2000);
  $("#stop").click(function() {
    window.clearInterval(intervalID);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="myButton" type='button'>
  This will change
</button>
<a id='stop' href='#'>Stop</a>

【讨论】:

    【解决方案2】:

    这是一种简洁、实用的方法。只是为了好玩。

    选择的答案是正确的。我只是提供另一种选择,使用稍微不同的风格。

    它启动、切换和停止。

    // "constant" array of messages
    var messagesArray = ['new Message', 'Some Btn'];
    
    // original button text
    var btnOrigText = $('button').text()
    
    // reverse an array
    var _arrReverse = function(arr) {
        return arr.reverse()
    }
    
    // insert text from array 0th index into an element
    var _insertTextArrayZero = function(el, messages) {
        // inserts an array's 0th index as HTML to an element
        return $(el).html(messages[0]);
    }
    
    // clears a timeout when given an id
    var _clearIntvlAt = function(intvlId) {
        return clearTimeout(intvlId);	
    }
    
    $(document).ready(function(){
        // set interval
        var intvl = 2000;
        // keep our original array intact
        var messagesCloned = messagesArray.slice(0)
        // run interval
        var toggleTextIntvl = setInterval(function() {
        	// insert reversed array from [0] index of array into HTML element
            // NOTE: this only works for arrays of 2 items which need to toggle
        	return _insertTextArrayZero('button', _arrReverse(messagesCloned))
        }, intvl);
         
        // initiate "stopping" of toggle text
        $('#stop').click(function() {
            // stop toggleTextIntvl
            _clearIntvlAt(toggleTextIntvl)
            // set markup back to default
            $('button').html(btnOrigText);
        });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button type='button'>
    This will change
    </button>
    <a id='stop' href='#'>Stop</a>

    【讨论】:

      【解决方案3】:

      之所以跳过new Message是因为:

      var someArray = {button: 'new Message', button: 'Some Btn'};
      

      您的someArray 是一个对象。因此,如果您具有相同的属性名称,它将被覆盖并被解析为

      var someArray = {button: 'Some Btn'};
      

      只要使用适当的结构就可以了

      var timeouts = [];
      
      var someArray = [{
        type: "button",
        message: 'new Message',
      }, {
        type: "button",
        message: 'Some Btn'
      }];
      
      $(document).ready(function() {
        var i = 2000;
        $.each(someArray, function(index, value) {
          timeouts.push(setTimeout(function() {
            $(value.type).html(value.message);
          }, i));
          i = i + 2000;
        });
      
      
        $('#stop').click(function() {
          $.each(timeouts, function(_, id) {
            clearTimeout(id);
          });
          timeouts = [];
          $(button).html('Some Btn');
        });
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <button type='button'>
        This will change
      </button>
      <a id='stop' href='#'>Stop</a>

      更新代码

      这就是我的写作方式。一些基本的变化,

      • 使用$(document).ready 作为代码流的开始。不是您的代码的包装器。它应该调用必要的函数。
      • 您应该使用Array.mapArray.forEach 而不是$.each()。这些功能非常强大和方便。
      • 在任何函数之外定义的变量都将成为全局范围的一部分。污染全局范围是一种不好的做法。
      • 使用小函数。这样,您可以重用代码的可能性更高。任何可以在其他地方使用的代码都可以用作函数。

      $(document).ready(function() {
        var someArray = [
          { type: "button", message: 'new Message', }, 
          { type: "button", message: 'Some Btn' }
        ];
      
        var timeouts = registerTimeouts(someArray);
        registerEvents(timeouts)
      });
      
      function registerTimeouts(array) {
        return array.map(function(value, index) {
          return setTimeout(function() {
            $(value.type).html(value.message);
          }, (index + 1) * 2000);
        });
      }
      
      function registerEvents(timeouts) {
        $('#stop').click(function() {
          timeouts.forEach(function(id) {
            clearTimeout(id);
          });
          timeouts = [];
          $(button).html('Some Btn');
        });
      }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <button type='button'>
        This will change
      </button>
      <a id='stop' href='#'>Stop</a>

      【讨论】:

        猜你喜欢
        • 2015-12-17
        • 1970-01-01
        • 1970-01-01
        • 2022-01-23
        • 2018-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-02
        相关资源
        最近更新 更多