关于javascript:JavaScript专项算法题4异步

25次阅读

共计 5197 个字符,预计需要花费 13 分钟才能阅读完成。

@冒泡的马树

题库原地址:http://csbin.io/async

异步

挑战一

问题:

思考工夫(当初临时不须要编写代码):剖析下方挑战一的代码,打印进去的后果会是怎么程序的?Howdy 先还是 Partnah 先?

题解:

/* CHALLENGE 1 */

function sayHowdy() {console.log('Howdy');
}

function testMe() {setTimeout(sayHowdy, 0);
  console.log('Partnah');
}
// After thinking it through, uncomment the following line to check your guess!
// testMe(); // what order should these log out? Howdy or Partnah first?

挑战二

问题:

构建 delayedGreet 函数,用于在 3 秒后打印“welcome”。

题解:

/* CHALLENGE 2 */

function delayedGreet() {
  // ADD CODE HERE
  setTimeout(()=>console.log('welcome'), 3000);
}
// Uncomment the following line to check your work!
// delayedGreet(); // should log (after 3 seconds): welcome

挑战三

问题:

构建 helloGoodbye 函数。其会立即打印”hello”,而后 2 秒后打印“good bye”。

代码:

/* CHALLENGE 3 */

function helloGoodbye() {
  // ADD CODE HERE
  setTimeout(()=>console.log('good bye'), 2000);
  console.log('hello');
}
// Uncomment the following line to check your work!
// helloGoodbye(); // should log: hello // should also log (after 3 seconds): good bye

挑战四

问题:

构建 brokenRecord 函数。其会每秒钟都打印一次”hi again“。应用”End Code“按钮完结打印如果你对代码的运行称心的话。(译注:原题库网页上的按钮)

题解:

/* CHALLENGE 4 */

function brokenRecord() {
  // ADD CODE HERE
  setInterval(()=>console.log('hi again'), 1000);
}
// Uncomment the following line to check your work!
// brokenRecord(); // should log (every second): hi again

挑战五

问题:

构建 limitedRepeat 函数。其会每秒钟打印一次”hi for now”,但仅仅继续 5 秒钟。如果你感到艰难的话,钻研 clearInterval。

题解:

/* CHALLENGE 5 */

function limitedRepeat() {
  // ADD CODE HERE
  const intervalId = setInterval(()=>console.log('hi for now'), 1000);
  setTimeout(()=>clearInterval(intervalId), 5000);
}
// Uncomment the following line to check your work!
// limitedRepeat(); // should log (every second, for 5 seconds): hi for now

挑战六

问题:

构建 everyXsecsForYsecs 函数。其承受三个参数:一个函数 func、一个数字 interval 和另外一个数 duration。

everyXsecsForYsecs 函数会以 interval 秒的距离运行函数 func, 但会在 duration 秒后完结运行。

题解:

/* CHALLENGE 6 */

function everyXsecsForYsecs(func, interval, duration) {
  // ADD CODE HERE
  const intervalId = setInterval(func, interval * 1000);
  setTimeout(() => clearInterval(intervalId), duration * 1000);
  
}
// Uncomment the following lines to check your work!
function theEnd() {console.log('This is the end!');
}
everyXsecsForYsecs(theEnd, 2, 20); // should invoke theEnd function every 2 seconds, for 20 seconds): This is the end!

挑战七

问题:

构建 delayCounter 函数,承受的第一个参数为一个数组(称为 target),第二个参数为毫秒单位的数字(称为 wait),返回后果为一个函数。

当返回函数被调用时,它会以依序打印从 1 到 target 之间的数字(含 target),以 wait 毫秒的工夫距离。

题解:

/* CHALLENGE 7 */

function delayCounter(target, wait) {
    // Solution 1:
    let intervalId;
    let counter = 0;
    return function inner() {if (counter === 0) {
        counter++;
        intervalId = setInterval(() => console.log(inner()), wait);
        } else if (counter === target) {clearInterval(intervalId);
        return counter;
        } else {return counter++;}
    }
    
      // Solution 2:
    //return function inner() {//    for(let i = 1; i<=target; i++){//  setTimeout(()=>console.log(i), wait * i);
    //    }
    //}
}

// UNCOMMENT THESE TO TEST YOUR WORK!
// const countLogger = delayCounter(3, 1000)
// countLogger();
// After 1 second, log 1
// After 2 seconds, log 2
// After 3 seconds, log 3

挑战八

问题:

构建 promised 函数,承受一个值作为参数。它会返回一个在两秒后触发 resolve 函数的 Promise 对象。

提醒:到 MDN 去查阅下 Promise 对象的文档。

题解:

/* CHALLENGE 8 */

function promised (val) {
  // ADD CODE HERE
  const promiseObj = new Promise((resolve) => {setTimeout(() => resolve(val), 2000);
  });
  return promiseObj;
}

// UNCOMMENT THESE TO TEST YOUR WORK!
// const createPromise = promised('wait for it...');
// createPromise.then((val) => console.log(val)); 
// will log "wait for it..." to the console after 2 seconds

挑战九

问题:

编写一个 SecondClock 类。其有两个办法:start 和 reset。

start:当调用时,start 会每秒调用一个回调函数(this.cb,在结构器中定义),作用于一个变量。这个变量每次被回调函数应用时总是以后的工夫秒数。

换言之,此回调函数每一秒钟都基于时钟信号的秒数而被调用,总是从 1 开始但并不应用以后计算机上的时钟信号的秒数值。

第一次“滴答”(值为 1)产生在最后的 secondClock 调用的 1 秒后;

第二次“滴答”(值为 2)产生在最后的 secondClock 调用的 2 秒后;

……

第六十次“滴答”(值为 60)产生在最后的 secondClock 调用的 60 秒后;

第六十一次“滴答”(值为 61)产生在最后的 secondClock 调用的 61 秒后;

第六十二次“滴答”(值为 62)产生在最后的 secondClock 调用的 62 秒后;

以此类推。

reset:当调用时,齐全进行 SecondClock 时钟的运行,另外重设工夫为初始值。

提醒:查阅 setInterval 和 clearInterval。

题解:

/* CHALLENGE 9 */

class SecondClock {constructor(cb) {
    // ADD CODE HERE
    this.counter = 0
    this.intervalId = 0
    this.cb = cb
  }
  // ADD METHODS HERE
  start () {this.intervalId = setInterval(()=>this.cb(++this.counter), 1000);
  }
  
  reset () {clearInterval(this.intervalId);
    this.counter = 0;
    this.intervalId = 0;
  }
}

// UNCOMMENT THESE TO TEST YOUR WORK!
// const clock = new SecondClock((val) => {console.log(val) });
// console.log("Started Clock.");
// clock.start();
// setTimeout(() => {//     clock.reset();
//     console.log("Stopped Clock after 6 seconds.");
// }, 6000);

挑战十

问题:

构建 debounce 函数,承受参数为一个回调函数 callback 和一个数值 interval,返回后果为一个函数。此返回函数仅会在其上次调用回调函数的 interval 毫秒后才会被再次调用回调函数。

在 interval 毫秒工夫内调用返回函数不会被响应或列入队列,然而工夫信息会被重置(译注:interval 工夫从新开始计算)。

无关防抖函数的例子:请查看这个链接 https://css-tricks.com/deboun…

题解:

/* CHALLENGE 10 */

function debounce(callback, interval) {
  // ADD CODE HERE
  // Solution 1:
  let timeCounter = 0
  let timeoutId = null
  return function() {if (timeCounter === 0) {timeoutId = setTimeout(()=>timeoutId = null, interval);
      timeCounter++;
        return callback();} else {if (timeoutId) {clearTimeout(timeoutId);
          timeoutId = setTimeout(()=>timeoutId = null, interval);
        timeCounter++;
      } else {
        timeCounter++;
        return callback();}
    }
  }
  
//   // Solution 2 (Not efficient): 
//   return function (){//     if (timeoutId) {//       clearTimeout(timeoutId);
//       timeoutId = setTimeout(() => timeoutId = null, interval);
//     } else {//       timeoutId = setTimeout(() => timeoutId = null, interval);
//       return callback();
      
//     }
//   }
}

// UNCOMMENT THESE TO TEST YOUR WORK!
function giveHi() { return 'hi';}
const giveHiSometimes = debounce(giveHi, 3000);
console.log(giveHiSometimes()); // -> 'hi'
setTimeout(function() {console.log(giveHiSometimes()); }, 2000); // -> undefined
setTimeout(function() {console.log(giveHiSometimes()); }, 4000); // -> undefined
setTimeout(function() {console.log(giveHiSometimes()); }, 8000); // -> 'hi'

正文完
 0