Skip to content

Instantly share code, notes, and snippets.

@mathdroid
Created December 21, 2020 06:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mathdroid/152ef4e5164e285dac4ce94cb5c56c5b to your computer and use it in GitHub Desktop.
Save mathdroid/152ef4e5164e285dac4ce94cb5c56c5b to your computer and use it in GitHub Desktop.
function main(callback1, callback2) {
callback1();
callback2();
callback2();
callback2();
}
function helloWorld() {
console.log("hello world");
}
function helloTelkomsel() {
console.log("hello telkomsel");
}
main(helloWorld, helloTelkomsel);
@mathdroid
Copy link
Author

[1:53 PM] Muhammad Mustadi
callback1 dipanggil 1x, setelah 2 detik
​[1:53 PM] Muhammad Mustadi
callback2 dipanggil 3x, interval 1 detik
​[1:57 PM] Muhammad Mustadi
setTimeout(fn, ms) // memanggil fn() setelah ms detik
​[1:57 PM] Muhammad Mustadi

setInterval(fn, ms) // memanggil fn() setiap ms detik

@mathdroid
Copy link
Author

let myInterval = setInterval(fn, ms)
clearInterval(myInterval)

@mathdroid
Copy link
Author

function main(callback1, callback2) {
  setTimeout(callback1, 2000);

  let interval = setInterval(function () {
    callback2();
  }, 1000);

  setTimeout(function () {
    clearInterval(interval);
  }, 3100);
}
function helloWorld() {
  console.log("hello world");
}

function helloTelkomsel() {
  console.log("hello telkomsel");
}

main(helloWorld, helloTelkomsel);

@mathdroid
Copy link
Author

function hoc() {
  return function () {
    console.log("hello world");
  };
}
// gimana cara kita tampilin hello world

@mathdroid
Copy link
Author

function multiplyWith(a) {
  return function (b) {
    return a * b;
  };
}

const triple = multiplyWith(3);
const result = triple(20);

console.log(result); // 60

@mathdroid
Copy link
Author

console.log("hello world");

setTimeout(function () {
  console.log("hello world 2");

  setTimeout(function () {
    console.log("hello world 3");
  }, 0);
}, 2500);

setTimeout(function () {
  console.log("hello world 4");

  setTimeout(function () {
    console.log("hello world 5");
  }, 2500);
}, 0);

console.log("hello world 6");

@mathdroid
Copy link
Author

let array = [20, 21, 22, 23];

for (let i = 0; i < array.length; i++) {
  setTimeout(function () {
    console.log("index:", i);
    console.log("element:", array[i]);
  }, 5000);
}

@mathdroid
Copy link
Author

let array = [20, 21, 22, 23];

let i;

for (i = 0; i < array.length; i++) {
  console.log(i);
  setTimeout(function logElement() {
    console.log("index:", i);
    console.log("element:", array[i]);
  }, 5000);
  console.log("incrementing i");
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment