Untitled
user_1671475754
javascript
4 years ago
2.7 kB
5
Indexable
//----------------1--------------------- const setSecondsTimeout = (cb,delay) => { return setTimeout(cb, delay * 1000); } setSecondsTimeout(function () { console.log('hello'); }, 1); // should print 'hello' after 1000 milliseconds setSecondsTimeout(function () { console.log('world'); }, 1.4); // should print 'world' after 1400 milliseconds //----------------2--------------------- let setSecondsTimeoutArgs = (cb, delay, ...args) => { setTimeout(cb, delay * 1000, ...args) } function printSum(num1, num2, num3) { console.log(num1 + num2 + num3); } setSecondsTimeoutArgs(printSum, 0.25, 5, 1, 4); // should print '10' after 250ms setSecondsTimeoutArgs(function (arg1, arg2) { console.log(arg1 + '-' + arg2); }, 0.7, 'hello', 'world'); // should print 'hello-world' after 700ms // ---------------3----------------------- const batchTimeouts = (cbsArr, delaysArr) => { const setTimeoutArr =[]; for(let i=0; i<cbsArr.length; i++){ let currentCb = cbsArr[i]; let currentDelay = delaysArr[i]; setTimeoutArr.push(setTimeout(currentCb, currentDelay)); } return setTimeoutArr; } // ------------------4---------------------- let intervalCount = (cb, delay, count) => { const intervalObj = setInterval(() => { cb(); count-- if (count === 0) clearInterval(intervalObj); }, delay) } intervalCount(function() { console.log('hi'); }, 500, 3); // prints 'hi' at 500ms intervals a total of 3 times //---------------------5---------------------- const postpone = (cb, delay) => { return () => { setTimeout(cb,delay); } } //------------------6----------------- let dynamicIntervalCount = (cb, delay, count) => { if (count === undefined) { return setInterval(cb, delay); } const obj = setInterval(() => { cb(); count-- if (count === 0) { clearInterval(obj); } }, delay) } dynamicIntervalCount(function () { console.log('hi'); }, 500, 3); // prints 'hi' at 500ms intervals a total of 3 times //------------7----------------- const postponeWithArgs = (cb, delay) => { return (...args) => { setTimeout(cb, delay, ...args ); } } const greet = (person) => console.log('Hello ' + person + '!'); const slowGreet = postponeWithArgs(greet, 1000); slowGreet('Rose'); // prints 'Hello Rose!' after 1000 ms slowGreet('Alex'); // prints 'Hello Alex!' after 1000 ms const printSum = (num1, num2) => console.log(num1 + num2); const slowPrintSum = postponeWithArgs(printSum, 500); slowPrintSum(4, 3); // prints '7' after 500 ms slowPrintSum(2, 8); // prints '10' after 500 ms
Editor is loading...