Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * SetTimeout
- */
- // 1 ==================================================
- (function() {
- console.log(1);
- setTimeout(function () { console.log(2) }, 1000);
- setTimeout(function () { console.log(3) }, 0);
- console.log(4);
- })();
- // 2 ==================================================
- // 0 - 4
- for (let i = 0; i < 5; i++) {
- setTimeout(function () { console.log(i) }, i*1000);
- }
- // 5*5
- for (var j = 0; j < 5; j++) {
- setTimeout(function () { console.log(j) }, j*1000);
- }
- /**
- * Объекты
- */
- // 1 ==================================================
- // 26
- const o = { b: 25 };
- const foo1 = (obj) => {
- obj.b = 26;
- };
- foo1(o);
- console.log(o.b);
- // 2 ==================================================
- var a = {};
- var b = {key: 'b'};
- var c = {key: 'c'};
- console.log('a: ', a);
- console.log('b: ', b);
- console.log('c: ', c);
- a[b] = 123;
- a[c] = 156;
- console.log(a[b]); // Объект преобразуется в строку [object Object], которая и становится ключом. Итог 156.
- /**
- * Функции
- */
- function sum(a, b) {
- if (b) return a + b;
- var currentSum = a;
- function f(c) {
- currentSum += c;
- return f;
- }
- f.toString = () => currentSum;
- return f;
- }
- console.log(sum(2,3)); // 5
- console.log(sum(2)(3)); // 5
- /**
- * Ассинхронные функции
- */
- function resolveAfter2seconds(x) {
- return new Promise(resolve => {
- setTimeout(() => {
- resolve(x);
- }, 1000);
- });
- }
- function resolveAfter5seconds(x) {
- return new Promise(resolve => {
- setTimeout(() => {
- resolve(x);
- }, 5000);
- });
- }
- // парарллельно
- async function addParallel(x) {
- const a = resolveAfter2seconds(20);
- const b = resolveAfter5seconds(30);
- return x + await a + await b;
- }
- // последовательно
- async function add(x) {
- const a = await resolveAfter2seconds(20);
- const b = await resolveAfter5seconds(30);
- return x + a + b;
- }
- add(10).then(result => console.log(result));
- addParallel(10).then(result => console.log(result));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement