Javascript:setTimeout在嵌套(双)for循环中关闭 [英] Javascript: setTimeout Closure inside nested (double) for loops

查看:172
本文介绍了Javascript:setTimeout在嵌套(双)for循环中关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我想尝试重新创建 http://austintexas.wayblazer.com/locations/ austin-tx 是为它的搜索文本框做的 - 显示输入的字符并在几个短语之间旋转。



我的初始逻辑是从数组中读取短语所以: [abc,123,XYZ] 然后使用 split forEach 将字符串分隔为字符,并使用 setTimeout 创建一个键入效果。



但是,当我尝试这个逻辑时,我似乎无法获得所需的效果。



希望的结果:我已经阅读过很多这些问题,但很少有人解决嵌套的for循环问题。




  • abc(按字符键入效果)

  • 清除文本框

  • 1 2 3(按字母键入效果字符)

  • 清除文本框

  • XYZ



实际结果:




  • abc123XYZ abc一次显示在一起,其次是123,然后是XYZ)



  $(document).ready(function(){$('input#123')。attr(placeholder,); var phrases = ['abc','123' XYZ']; for(var i = 0; i  

 < script src = //ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js\"> ;</script><input id =123/>  



有什么我想要实现的优雅的解决方案,希望一些解释,非常感谢!

解决方案

JavaScript的伟大的事情是闭包,所以你可以创建函数闭包,行为类似堆栈。然后你可以在setInterval内部关闭这些函数。



  $(document).ready(function(){var input = $('input#123'),phrases = ['Stack Overflow','Is the place you come' ],typedelay = 140,waitops = 5,cmds = [],ph = input.attr.bind(input,'placeholder'); function clear(){ph(''); } function addLetter(a){return function(){ph(ph()+ a); }} function doLoop(){cmds = []; for(var i = 0; i  

 < script src =https: /ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js\"> ;</script> ;<input id =123/>  


Hi I'm trying to recreate what http://austintexas.wayblazer.com/locations/austin-tx is doing for its search textbox - displaying typed character and rotating between several phrases.

My initial logic is to read the phrases from an array like so: [abc,123,XYZ] and then to use a split and forEach to separate the string into characters and create a typing effect using setTimeout.

However, when I attempt this logic, I seem to have trouble getting the desired effect. I've been reading through a lot of these questions on SO, but few of them address issues with nested for loops.

Desired results:

  • a b c (in a typing effect character by character)
  • clear textbox
  • 1 2 3 (in a typing effect character by character)
  • clear textbox
  • X Y Z

Actual results:

  • abc123XYZ (abc shows up together at once, followed by 123, then XYZ)

$(document).ready(function() {

  $('input#123').attr("placeholder", "");
  var phrases = ['abc', '123', 'XYZ'];

  for (var i = 0; i < phrases.length; i++) {
    $('input#123').attr("placeholder", "");
    (function(ind) {
      var sentence = phrases[ind];
      sentence.split("").forEach(function(char, index) {
        setTimeout(function() {
          $('input#123').attr("placeholder", $('input#123').attr("placeholder") + char);
        }, ind * 500);
      });
    })(i);
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input id="123" />

Is there an elegant solution for what I want to achieve, and hopefully some explanation to enlighten me would be very much appreciated!

解决方案

The great thing with javascript is closures, so you can create function closures, and push onto an array to act like a stack.. You can then pop these function off inside a setInterval..

$(document).ready(function(){
	var input = $('input#123'),
	    phrases = ['Stack Overflow','Is the place you come','To get help with coding stuff'],
        typedelay = 140,
        waitops = 5,
        cmds = [],
        ph = input.attr.bind(input, 'placeholder');
  
    function clear() {
      ph('');
    }
  
    function addLetter(a) {
      return function () {
        ph(ph() + a);
      }
    }
  
    function doLoop() {
      cmds = [];
      for (var i=0; i<phrases.length;i++) {
        cmds.push(clear);
        var sentence = phrases[i];
        sentence.split("").forEach(function(char,index) {
          cmds.push(addLetter(char));
        });
        //at the end of each sentence, there is a pause. lets do some no ops,.. 5*300 ms
        for (var nn = 0; nn < waitops; nn ++) cmds.push(0);
      }
      //lets make this thing go on forever.. :)
      cmds.push(doLoop);
    }
      
    doLoop();
  
    var icheck = setInterval(function () {
      //is there a cmd waiting, pop it and run it.
      var cmd = cmds.shift();
      if (cmd) { cmd(); }
    }, typedelay);
  
    input.focus(function () {
      clearInterval(icheck);
      cmds = [];
      ph('What your want');
    });
    
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input id="123" />

这篇关于Javascript:setTimeout在嵌套(双)for循环中关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆