简体   繁体   English

为什么我嵌套的 setTimeout 延迟不起作用?

[英]why my nested setTimeout delay not working?

When i scroll on my "frame-2" element, i wanted to change the words every 300ms.当我滚动“frame-2”元素时,我想每 300 毫秒更改一次单词。 the word change every 300ms and stop on each word of my array.单词每 300 毫秒更改一次,并在数组的每个单词上停止。

The scroll function works.滚动功能有效。 The stop on each word also works but the delay is not of 300ms isn't respected and word change almost instantly.每个单词的停止也有效,但延迟不是 300 毫秒,并且几乎立即更改单词。 Do you see a mistake that I do not see ?你看到一个我没有看到的错误吗?

function interval(func, wait, times){
    var interv = function(w, t){
      return function(){
        if(typeof t === "undefined" || t-- > 0){
          setTimeout(interv, w);
          try{
            func.call(null);
          }
          catch(e){
            t = 0;
            throw e.toString();
          }
        }
      };
    }(wait, times);

    setTimeout(interv, wait);
  };

  var words21 = ["communication.", "image.", "concept.", "référencement.", "stratégie.", "contenu.", "social média."];
  var text21 = "repensent votre <span class='surlignement-rouge-text'>communication.</span>";
  var i21;
  var wi21;

  function _getChangedText21() {
    i21 = (i21 + 1);
    if (words21[i21] != undefined) {
      return text21.replace(/communication./, words21[i21]);
    } else {
      return text21.replace(/communication./, words21[wi21]);
      wi21 = (wi21 + 1);
    }
  }

  $(window).scroll(function() {
    text21.replace(/communication./, words21[0]);
    i21 = 0;
    wi21 = 1;
    x = 0;
    var hT20 = $('#frame-2').offset().top,
        hH20 = $('#frame-2').outerHeight(),
        wH20 = $(window).height(),
        wS20 = $(this).scrollTop();

    if (wS20 > (hT20+hH20-wH20)) {
      interval(function _getInterval21() {
        interval(function _changeText21() {
          var txt21 = _getChangedText21();
          document.getElementById("changer2").innerHTML = txt21;
        }, 300, 8);
        selectwords21 = words21[0];
        words21.shift();
        words21.push(selectwords21);
      }, 2000, 6);
      selectwords21 = words21[0];
      words21.shift();
      words21.push(selectwords21);
      selectwords21 = words21[0];
      words21.shift();
      words21.push(selectwords21);
    }
  });

Thx a lot, BadWoo非常感谢,BadWoo

Edit : here is a codepen exemple : https://codepen.io/BadWoo/pen/MWyQbPB编辑:这是一个代码笔示例: https ://codepen.io/BadWoo/pen/MWyQbPB

First of all t will never be "undefined" , but it can be undefined .首先t永远不会是"undefined" ,但它可以是undefined And second, instead of calling setTimeout(interv, wait) do setTimeout(interv(), wait) , because interv returns a function, and that's what you want to execute.其次,不要调用setTimeout(interv, wait)setTimeout(interv(), wait) ,因为 interv 返回一个函数,这就是你想要执行的。

If all you're trying to do is change the text inside changer2 for a rotating list of words in place of "communication."如果您想要做的只是更改changer2的文本,以使用轮换的单词列表代替“交流”。 you could do this in a few lines of code (See example below).您可以在几行代码中完成此操作(请参见下面的示例)。

  • No need to keep shifting and pushing words -- just use modulo operator %无需不断移动和推动单词 - 只需使用模运算符%
  • No need to have nested calls to a setTimout - use setInterval无需嵌套调用setTimout - 使用setInterval

Assuming I've understood correctly what you're trying to achieve here's the working code (adjust the timing as desired):假设我已经正确理解了您要实现的目标,这是工作代码(根据需要调整时间):

 function changeWords(){ var words = ["communication.", "image.", "concept.", "référencement.", "stratégie.", "contenu.", "social média."]; var i = 1; setInterval( () => { document.querySelector('.surlignement-rouge-text').innerHTML = words[i++ % words.length]; }, 1000); } // You could call this from your scroll handler! changeWords();
 .surlignement-rouge-text{ color: red }
 <span id="changer2">repensent votre <span class='surlignement-rouge-text'>communication.</span></span>

Having further understood your requirement, it seems the code does need to be a little more complex but not much!还具有了解您的要求,似乎代码确实需要一个稍微复杂一些,但并不多!

 var words = ["communication.", "image.", "concept.", "référencement.", "stratégie.", "contenu.", "social média."]; async function changeWords(interval){ return new Promise( resolve => { var i = 0; var timer = setInterval( () => { document.querySelector('.surlignement-rouge-text').innerHTML = words[i++]; if(i == words.length){ clearInterval(timer); resolve(); } }, interval); }); } async function cycleWords(shortInterval, longInterval, i){ await changeWords(shortInterval); document.querySelector('.surlignement-rouge-text').innerHTML = words[i % words.length]; setTimeout(() => cycleWords(shortInterval,longInterval, i+1),longInterval); } // You could call this from your scroll handler! cycleWords(300,2000,0);
 .surlignement-rouge-text{ color: red }
 <span id="changer2">repensent votre <span class='surlignement-rouge-text'>communication.</span></span>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM