簡體   English   中英

如何正確地將 setInterval/setTimeout 添加到我的函數中

[英]How to properly add setInterval/setTimeout to my function

請幫忙!

該函數應將字母“A”到“F”打印到控制台,每秒一個字母。

該函數在沒有 setInterval/setTimeout 的情況下工作。

// setInterval(alphabet, 1000, 'a', 'f');

function alphabet(from, to) {
  var a = [], i = from.charCodeAt(0), j = to.charCodeAt(0);
  for (; i <= j; ++i) {
    setInterval(() => {
      a.push(String.fromCharCode(i));
    }, 1000);
  }
  // return console.log(a);
  return a;
}

console.log(alphabet('a', 'f'));

 function printLetters(start, finish) { //should add checks here to validate start comes before finish console.log(start) if (start == finish) { return } else { setTimeout(printLetters, 1000, String.fromCharCode(start.charCodeAt(0)+1), finish) } } printLetters('a', 'f')

你可能想試試這個。 你可以把它粘貼到codepen上

var a = [];
function alphabet(from, to) {
    console.log(a);
    setInterval(() => {
        var i = from.charCodeAt(0);
        var j = to.charCodeAt(0);
        for (; i <= j; ++i) {
          if(a.includes(String.fromCharCode(i))){
             
          }else{
            console.log(String.fromCharCode(i))
            a.push(String.fromCharCode(i));
            break;
          }
        }
    }, 1000);
  return a;
}

alphabet('a', 'f');

這是使用async 睡眠功能的解決方案。

 function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function alphabet(from,to){ var currentLetter = from[0]; while(currentLetter.charCodeAt(currentLetter[0]) != to.charCodeAt(to[0])+1){ let l = currentLetter await sleep(1000) console.log(l) nextLetter = String.fromCharCode(currentLetter.charCodeAt(currentLetter[0])+1) currentLetter = nextLetter; } } alphabet('A','F');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM