简体   繁体   English

更改setTimeout循环的延迟

[英]Changing delay for setTimeout loop

Currently I have a string of letters and numbers that get split into an array and then display one by one separated by a set amount of time defined by the user. 目前,我有一串字母和数字,它们被分成一个数组,然后一一显示,并按用户定义的固定时间间隔显示。 I've run into a problem though, before I initialize myFunction(), I am able to set the number of letters/numbers that are displayed per minute, but once the function is running I cannot change the speed. 但是,在初始化myFunction()之前,我遇到了一个问题,我可以设置每分钟显示的字母/数字的数量,但是一旦函数运行,我就无法更改速度。 How would I modify my code to allow me to change the speed up or down while the function is already running. 在功能已经运行的情况下,我将如何修改代码以允许我提高或降低速度。

 var string = "33 a 52 20 82 86 81 7 96 86 c 25 29 44 64 77 D 40 32 55 50 L 65 48 35 21 85 y 46 88 63 55 u 48 65 6 17 37 e 51 53 47 50 a 16 72 M 64 80 P 54 w 43 f 4 67 32 55 79 29 62 11 32 g 47 78 38 42 59 92 x 15 43 61 92 50 57 31 Z 84 69 80 32 9 m 98 22 83 19 12 21 37 28 63 42 73 88 84 75 60"; function myFunction() { var array = string.split(' '); for (var i = 0; i < array.length; i++) { var delay = 60000/(document.getElementById('numPerMinute').value); (function (str) { setTimeout(function () { document.getElementById("displayResults").innerHTML = str; }, delay * i); })(array[i]); } } 
 <button onclick="myFunction()">Run</button> <input type="number" id="numPerMinute"/> <div id="displayResults"></div> 

You can invoke a new timeout recursively after the previous one has finished. 您可以在前一个超时结束后递归调用新超时。 This way the delay is calculated each time just before a new timeout starts. 这样,每次在新超时开始之前就计算延迟。

 var string = '33 a 52 20 82 86 81 7 96 86 c 25 29 44 64 77 D 40 32 55 50 L 65 48 35 21 85 y 46 88 63 55 u 48 65 6 17 37 e 51 53 47 50 a 16 72 M 64 80 P 54 w 43 f 4 67 32 55 79 29 62 11 32 g 47 78 38 42 59 92 x 15 43 61 92 50 57 31 Z 84 69 80 32 9 m 98 22 83 19 12 21 37 28 63 42 73 88 84 75 60'; var btn = document.getElementById('btn'); btn.addEventListener("click", function() { var results = document.getElementById('displayResults'); var array = string.split(' '); this.disabled = true; results.innerHTML = '...'; function startDelay() { var numPerMinute = parseInt(document.getElementById('numPerMinute').value); if (!numPerMinute) { // Invalid input btn.disabled = false; return; } var delay = 60000 / numPerMinute; setTimeout(function() { results.innerHTML = array.shift(); startDelay(); }, delay); } startDelay(); }); 
 <button id="btn">Run</button> <input id="numPerMinute" type="number" value="30"> <div id="displayResults"></div> 

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

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