Setinterval di untuk loop javascript

Saat bekerja dengan Node. js sangat penting untuk memahami Node's Event Loop dan fase-fasenya. Fase pertama dari Event Loop Node adalah timer, dan panggilan baliknya. Memahami penghitung waktu, dan kapan panggilan baliknya dipanggil, adalah langkah pertama untuk memahami eksekusi kode terjadwal. Ini memungkinkan kita untuk lebih mengontrol kontinum waktu aplikasi kita. Di Node. timer js dapat diatur dengan dua fungsi utama

const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
8 dan
const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
9

Dalam tutorial ini kita akan

  • Lebih lanjut pengetahuan kita tentang fase pengatur waktu dari Node. js Event Loop melalui eksplorasi contoh kode
  • Pelajari konsep penjadwalan kode dan cara melakukannya dengan
    const alert = "We are ready; start the movie";
    
    // This is what we see in the console first.
    console.log("This is a pre-show ad reel.. It's running");
    
    // setTimeout() function with anonymous callback
    // and delay in milliseconds.
    setTimeout(() => {
      console.log(alert);
    }, 5000);
    
    8 dan
    const alert = "We are ready; start the movie";
    
    // This is what we see in the console first.
    console.log("This is a pre-show ad reel.. It's running");
    
    // setTimeout() function with anonymous callback
    // and delay in milliseconds.
    setTimeout(() => {
      console.log(alert);
    }, 5000);
    
    9
  • Dapatkan pemahaman tentang waktu eksekusi callback dan perbedaan antar timer dalam konteks Node.js. js dan browser

Pada akhir tutorial ini, Anda harus dapat menjelaskan bagaimana penghitung waktu yang dibuat dengan

const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
8 dan
const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
9 berhubungan dengan Node. js Acara Loop

Sasaran

Pelajari cara menggunakan

const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
8 dan
const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
9 dalam kode Anda dan amati eksekusi callback mereka selama eksekusi Event Loop

Prasyarat

Menjadwalkan panggilan balik satu kali dengan const alert = "We are ready; start the movie"; // This is what we see in the console first. console.log("This is a pre-show ad reel.. It's running"); // setTimeout() function with anonymous callback // and delay in milliseconds. setTimeout(() => { console.log(alert); }, 5000); 8

const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
8 adalah pengatur waktu satu kali yang memungkinkan kita menjadwalkan kode untuk dijalankan setelah jangka waktu tertentu

Contoh

setTimeout(function, delay, [arg1], [arg2], ...);

Fungsi

const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
8 membutuhkan dua argumen utama

  • $ node timers.js
    
    _9. Fungsi panggilan balik yang perlu dipanggil saat waktu tunda habis
  • $ node timers.js
    This is a pre-show ad reel.. It\'s running
    
    0. Jumlah milidetik untuk menunda sebelum menelepon
    $ node timers.js
    
    9

Argumen tambahan apa pun akan diteruskan ke fungsi callback saat dijalankan

Bayangkan Anda berada di bioskop, dan akan menonton film. Anda bersemangat, tetapi Anda terjebak menonton pra-pertunjukan karena petugas film sedang menunggu isyarat untuk memutar film

Mari jalankan skenario ini di konsol. Buat file bernama timer. js. Dalam file ini tentukan variabel

$ node timers.js
This is a pre-show ad reel.. It\'s running
_2 yang akan memberi tahu petugas film untuk memulai film saat masa tunggu pra-pertunjukan habis. Tambahkan penghitung waktu dengan
$ node timers.js
This is a pre-show ad reel.. It\'s running
_0 disetel ke durasi pra-pertunjukan

Kode Anda mungkin terlihat seperti ini

const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);

Setelah siap, jalankan kode Anda dengan perintah

$ node timers.js

Di konsol pada awalnya kami melihat teks gulungan demo pra-pertunjukan kami

$ node timers.js
This is a pre-show ad reel.. It\'s running

Kemudian setelah

$ node timers.js
This is a pre-show ad reel.. It\'s running
_0 kami melihat bahwa petugas film kami mendapat sinyal dan film akan segera dimulai

$ node timers.js
This is a pre-show ad reel.. It\'s running
We are ready; start the movie

Mari kita lihat apa yang terjadi di sini dari perspektif Event Loop. Proses aplikasi kami dimulai dan memasuki Event Loop. Itu pergi ke fase pertama - "timer" - di mana ia memeriksa callback timer. Pada awalnya kami tidak punya;

Event Loop berlanjut ke fase selanjutnya. "I/O callback", "idle", dan terakhir, "polling". Pada fase "polling", Event Loop mengeksekusi

$ node timers.js
This is a pre-show ad reel.. It\'s running
6 pertama kami dengan teks gulungan iklan. Kemudian menekan panggilan ke
const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
_8 dan mendorong panggilan baliknya ke antrean penghitung waktu dan melanjutkan ke fase berikutnya dari Event Loop

Karena kami tidak memiliki kode lain setelah

const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
8, tetapi kami masih menunggu pengatur waktu yang saat ini dalam antrean, kode menjadi tidak aktif pada fase panggilan balik
$ node timers.js
This is a pre-show ad reel.. It\'s running
9. Event Loop tertidur dan dibangunkan saat penundaan pengatur waktu habis. Kemudian ia memulai centang berikutnya dengan fase penghitung waktu dan mengeksekusi panggilan balik

Setelah itu, dilanjutkan melalui fase Event Loop hingga mencapai fase

$ node timers.js
This is a pre-show ad reel.. It\'s running
9 lagi, menyadari bahwa tidak ada lagi kode yang harus dieksekusi, dan tidak ada lagi antrian timer. Oleh karena itu beralih ke fase "close events" dan mengeksekusi
$ node timers.js
This is a pre-show ad reel.. It\'s running
We are ready; start the movie
1 menyelesaikan runtime aplikasi kita

Tangkapannya di sini adalah untuk memahami bahwa

$ node timers.js
This is a pre-show ad reel.. It\'s running
_0 diteruskan ke
const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
8 adalah penundaan minimum dan mungkin memerlukan lebih banyak waktu sebelum panggilan balik dijalankan. Katakanlah film seharusnya dimulai pukul 2. 30 PM, dan panjang gulungan iklan kami adalah 10 menit. Itu berarti asisten film harus memulai gulungan iklan di 2. 20 tajam -- tetapi hari ini mereka merasa tidak enak badan dan tidak memulai gulungan iklan sampai jam 2. 25. Mereka tidak dapat memulai film sampai gulungan iklan selesai karena sponsor membayar iklan untuk dilihat. Jadi film tidak akan bisa mulai jam 2. 20, meskipun waktunya sudah habis

Mari kita lihat ini dalam kode. Di pengatur waktu. js, ubah

$ node timers.js
This is a pre-show ad reel.. It\'s running
_0 agar pengatur waktu kita menjadi 10 milidetik -- sangat singkat, hampir seketika -- dan jalankan kode Anda. Perhatikan bahwa Anda hampir tidak bisa membedakan konsol, dan kedua pesan konsol mengikuti satu sama lain hampir tanpa penundaan. Sekarang mari kita meniru penundaan pemutaran iklan. Buat fungsi dengan kode berikut dan panggil setelah
const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
8

Mengedit pengatur waktu. js

const alert = "We are ready, start the movie";

// Emulation of the demo (ad) reel.
const demoReel = () => {
  const length = 500000000;
  let sum = 0;
  for (i = 0; i <= length; i++) {
    sum += i;
  }
};
// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 10);
demoReel();

Kemudian jalankan kode dengan perintah berikut

$ node timers.js

Perhatikan bagaimana di konsol pesan "film siap dimulai" kami tidak lagi ditampilkan secara instan. Callback timer berada dalam antrean fase timer dari Event Loop tetapi fungsi

$ node timers.js
This is a pre-show ad reel.. It\'s running
We are ready; start the movie
6 memblokir tumpukan pada fase "polling" saat
$ node timers.js
This is a pre-show ad reel.. It\'s running
We are ready; start the movie
7 loop sedang berjalan

Timer menunggu hingga dieksekusi, lalu fase

$ node timers.js
This is a pre-show ad reel.. It\'s running
9 terjadi;

Menjadwalkan callback berulang dengan const alert = "We are ready; start the movie"; // This is what we see in the console first. console.log("This is a pre-show ad reel.. It's running"); // setTimeout() function with anonymous callback // and delay in milliseconds. setTimeout(() => { console.log(alert); }, 5000); 9

Dalam situasi ketika Anda harus dapat mengeksekusi blok kode berulang kali, timer

const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
9 adalah opsi yang lebih baik. Dibutuhkan argumen yang sama dengan
const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
8. fungsi
$ node timers.js
_9 dan
$ node timers.js
This is a pre-show ad reel.. It\'s running
0 dalam milidetik. Implementasi internal
const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
_9 mendekati
const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
8 dengan pengecualian bendera pengulangan internal yang disetel ke
const alert = "We are ready, start the movie";

// Emulation of the demo (ad) reel.
const demoReel = () => {
  const length = 500000000;
  let sum = 0;
  for (i = 0; i <= length; i++) {
    sum += i;
  }
};
// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 10);
demoReel();
7 untuk
const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
9

Mari kita kembali ke bioskop. Bayangkan kami berdebat tentang film apa yang harus ditonton dan akhirnya terlambat. Semua kursi sepertinya sudah terjual habis dan sepertinya kita akan ketinggalan. Namun, biasanya teater ini merilis beberapa tiket menjelang dimulainya pertunjukan secara online. Kami ingin memeriksa apakah ada kursi yang tersedia, sekali setiap detik, dan jika ada dua atau lebih maka pesanlah tiketnya. Kode untuk melakukan itu terlihat seperti berikut

Mengedit pengatur waktu. js sehingga berisi kode ini

// This function emulates us checking available seats.
const getEmptySeats = () => {
  return Math.round(3 * Math.random());
};

// We would like to check every second.
setInterval(() => {
  let seats = getEmptySeats();
  if (seats === 1) {
    console.log(`There is currently ${seats} seat available`);
  } else if (seats === 0) {
    console.log(
      "Oh nooooo, no available seats, looks like we will miss the movie!"
    );
  } else if (seats >= 2) {
    console.log(`${seats} seats are available, book them, quickly!`);
  }
}, 1000);

Kami membuat fungsi pengacak emulasi di bagian atas yang memungkinkan kami mensimulasikan hasil pemeriksaan kursi yang tersedia secara online. Ini akan mengembalikan angka dari 0 hingga 3. Mari jalankan kode kita dan periksa hasilnya

Dalam menjalankan terminal

node timers.js
2 seats are available, book them, quickly!
3 seats are available, book them, quickly!
3 seats are available, book them, quickly!
Oh nooooo, no available seats, looks like we will miss the movie!
2 seats are available, book them, quickly!
2 seats are available, book them, quickly!
2 seats are available, book them, quickly!
There is currently 1 seat available

Kode ini akan berjalan hingga Anda keluar dari proses secara manual dengan

const alert = "We are ready, start the movie";

// Emulation of the demo (ad) reel.
const demoReel = () => {
  const length = 500000000;
  let sum = 0;
  for (i = 0; i <= length; i++) {
    sum += i;
  }
};
// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 10);
demoReel();
9

Seperti yang Anda lihat, timer sedang berjalan dan kami melihat keluaran konsol. Bagaimana cara kerjanya dalam hal Event Loop? . Lain kali Event Loop berada dalam fase pengatur waktu, callback ini akan dijalankan, asalkan waktu tunda habis. Selama fase polling, panggilan balik akan ditambahkan kembali ke antrean berulang kali karena tanda pengulangan

Saat Anda menjalankan kode, Anda melihat bahwa proses tidak berhenti, berapa pun waktu yang telah berlalu sejak awal eksekusi. Di dunia nyata kita pasti sudah memesan tiket ketika kita melihat pesan pertama dan pergi menonton film. Alasan pengatur waktu tidak berhenti adalah karena libUV memeriksa selama fase "polling" jika ada panggilan balik yang belum selesai. Karena ia melihat

const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
_9 ia tidak pernah keluar dari Event Loop dan eksekusi program kami tidak pernah berakhir

Jika kami ingin berhenti memeriksa segera setelah kebutuhan kami akan tiket terpenuhi, kami perlu memberi tahu aplikasi kami bahwa pengatur waktu harus menghentikan eksekusi. Ada banyak cara untuk melakukan ini. Mari jelajahi semuanya terkait dengan Event Loop

Pertama kita dapat menggunakan

$ node timers.js
This is a pre-show ad reel.. It\'s running
We are ready; start the movie
_1 untuk menghentikan proses. Mari ubah kode kita di timer. js untuk mengilustrasikan ini

const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
0

Perhatikan bahwa kita memiliki

$ node timers.js
This is a pre-show ad reel.. It\'s running
We are ready; start the movie
1 dalam kondisi sukses kita. Mari jalankan kode di terminal

$ node timers.js
const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
2

Berhasil. Namun, solusi ini hanya dapat diterima jika kita terlambat menonton film karena di sini kita mematikan seluruh eksekusi runtime -- bukan cara yang paling elegan untuk mengakhiri sesuatu

Dari perspektif Event Loop -- ini diakhiri bersamaan dengan seluruh proses/runtime aplikasi

Node. js memiliki mekanisme yang memungkinkan Anda menghapus pengatur waktu. Mengedit pengatur waktu. file js lagi

const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
_3

Pertama, kita perlu menyimpan referensi ke timer kita. Lakukan ini dengan menetapkan nilai pengembalian

const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
9 ke sebuah variabel. Kemudian saat kita siap untuk menghapus pengatur waktu, kita meneruskan referensi ini ke fungsi
$ node timers.js
6

Jalankan di terminal Anda dengan

$ node timers.js
const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
5

Apa yang terjadi di sini dari perspektif Event Loop? . Saat penundaan habis dan Event Loop berada di fase "timer", callback dijalankan dan kami melihat pesan konsol. "Saat ini tersedia 1 kursi". Ini tidak memenuhi kebutuhan kami dan Event Loop berlanjut ke tahap selanjutnya, kembali ke polling di mana callback dikirim ke antrean penghitung waktu lagi

Kali ini, ketika penundaan habis selama fase pengatur waktu, panggilan balik dipanggil lagi dan hasil pemeriksaannya positif -- kami melihat 2 kursi tersedia. Kami berlari untuk memesan tiket, sambil memberi tahu libUV bahwa pengatur waktu dapat dihapus sehingga panggilan baliknya tidak berakhir di antrian pengatur waktu sekali lagi. Event Loop melewati semua fase yang tersisa, tidak menemukan kode lagi untuk dieksekusi, dan menghentikan eksekusi proses

Sejauh ini bagus, tetapi ada Node.js yang lebih elegan. cara khusus js untuk menghentikan timer. Perhatikan, tidak seperti

$ node timers.js
_6 ini tidak akan berfungsi di browser. Di Node. js, tidak seperti browser, pengatur waktu adalah sebuah objek dan ketika dipanggil itu direferensikan di libUV. Dalam fase pengatur waktu dari Event Loop, semua pengatur waktu yang direferensikan diperiksa untuk panggilan balik. Jika kita membatalkan referensi pengatur waktu, kita memberi tahu libUV bahwa pengatur waktu ini dan panggilan baliknya tidak penting lagi dan dapat diabaikan selama fase pengatur waktu

Mari kita lihat ini beraksi. Kami masih membutuhkan referensi ke pengatur waktu di awal. Nanti, alih-alih memanggil

$ node timers.js
_6 kita akan memanggil
// This function emulates us checking available seats.
const getEmptySeats = () => {
  return Math.round(3 * Math.random());
};

// We would like to check every second.
setInterval(() => {
  let seats = getEmptySeats();
  if (seats === 1) {
    console.log(`There is currently ${seats} seat available`);
  } else if (seats === 0) {
    console.log(
      "Oh nooooo, no available seats, looks like we will miss the movie!"
    );
  } else if (seats >= 2) {
    console.log(`${seats} seats are available, book them, quickly!`);
  }
}, 1000);
0 dari objek pengatur waktu

const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
6
const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
7

Seperti yang Anda lihat, di sini kami melakukan panggilan balik beberapa kali hingga kami mencapai kondisi yang memenuhi kebutuhan kami. Dalam hal ini kami memberi tahu libUV bahwa kami tidak peduli lagi dengan pengatur waktu ini. Timer terus berjalan tetapi selama fase "polling", panggilan baliknya tidak ditandai sebagai luar biasa dan dimasukkan ke dalam antrean timer. Eksekusi runtime mendeteksi bahwa tidak ada lagi kode yang beredar dan prosesnya berhenti

Kedua metode,

$ node timers.js
_6 dan
// This function emulates us checking available seats.
const getEmptySeats = () => {
  return Math.round(3 * Math.random());
};

// We would like to check every second.
setInterval(() => {
  let seats = getEmptySeats();
  if (seats === 1) {
    console.log(`There is currently ${seats} seat available`);
  } else if (seats === 0) {
    console.log(
      "Oh nooooo, no available seats, looks like we will miss the movie!"
    );
  } else if (seats >= 2) {
    console.log(`${seats} seats are available, book them, quickly!`);
  }
}, 1000);
2, dapat diterima. Namun, fungsi
$ node timers.js
_6 sepenuhnya menghentikan eksekusi timer, mencegah callback berjalan. Fungsi
// This function emulates us checking available seats.
const getEmptySeats = () => {
  return Math.round(3 * Math.random());
};

// We would like to check every second.
setInterval(() => {
  let seats = getEmptySeats();
  if (seats === 1) {
    console.log(`There is currently ${seats} seat available`);
  } else if (seats === 0) {
    console.log(
      "Oh nooooo, no available seats, looks like we will miss the movie!"
    );
  } else if (seats >= 2) {
    console.log(`${seats} seats are available, book them, quickly!`);
  }
}, 1000);
_2 bertindak lebih seperti bendera. Pada saat Event Loop aktif maka timer callback akan berjalan seperti biasa, namun jika timer tersebut adalah yang terakhir dalam antrian aktif maka Event Loop tidak akan berjalan dan akan exit

Hal ajaib tentang metode

// This function emulates us checking available seats.
const getEmptySeats = () => {
  return Math.round(3 * Math.random());
};

// We would like to check every second.
setInterval(() => {
  let seats = getEmptySeats();
  if (seats === 1) {
    console.log(`There is currently ${seats} seat available`);
  } else if (seats === 0) {
    console.log(
      "Oh nooooo, no available seats, looks like we will miss the movie!"
    );
  } else if (seats >= 2) {
    console.log(`${seats} seats are available, book them, quickly!`);
  }
}, 1000);
_2 adalah pengatur waktu dapat ditandai sebagai aktif lagi dengan menggunakan fungsi saudaranya
// This function emulates us checking available seats.
const getEmptySeats = () => {
  return Math.round(3 * Math.random());
};

// We would like to check every second.
setInterval(() => {
  let seats = getEmptySeats();
  if (seats === 1) {
    console.log(`There is currently ${seats} seat available`);
  } else if (seats === 0) {
    console.log(
      "Oh nooooo, no available seats, looks like we will miss the movie!"
    );
  } else if (seats >= 2) {
    console.log(`${seats} seats are available, book them, quickly!`);
  }
}, 1000);
6 dipanggil pada objek pengatur waktu

Gunakan fungsi

// This function emulates us checking available seats.
const getEmptySeats = () => {
  return Math.round(3 * Math.random());
};

// We would like to check every second.
setInterval(() => {
  let seats = getEmptySeats();
  if (seats === 1) {
    console.log(`There is currently ${seats} seat available`);
  } else if (seats === 0) {
    console.log(
      "Oh nooooo, no available seats, looks like we will miss the movie!"
    );
  } else if (seats >= 2) {
    console.log(`${seats} seats are available, book them, quickly!`);
  }
}, 1000);
_7 saat Anda ingin menghentikan pengatur waktu sepenuhnya; . Namun pastikan Anda tidak menggunakan metode ini secara berlebihan;

Dalam kebanyakan kasus,

$ node timers.js
_6 dan
node timers.js
0 adalah apa yang ingin Anda gunakan. Menggunakan
// This function emulates us checking available seats.
const getEmptySeats = () => {
  return Math.round(3 * Math.random());
};

// We would like to check every second.
setInterval(() => {
  let seats = getEmptySeats();
  if (seats === 1) {
    console.log(`There is currently ${seats} seat available`);
  } else if (seats === 0) {
    console.log(
      "Oh nooooo, no available seats, looks like we will miss the movie!"
    );
  } else if (seats >= 2) {
    console.log(`${seats} seats are available, book them, quickly!`);
  }
}, 1000);
_0 dapat menyebabkan perilaku yang tidak dapat diprediksi dalam aplikasi Anda di mana callback dapat atau tidak dapat dieksekusi sekali lagi berdasarkan keadaan Event Loop

Rekap

Dalam tutorial ini kita terjun ke fase pengatur waktu dari Event Loop melalui berbagai contoh. Kami mempelajari bahwa untuk menjadwalkan eksekusi callback satu kali, gunakan

const alert = "We are ready; start the movie";

// This is what we see in the console first.
console.log("This is a pre-show ad reel.. It's running");

// setTimeout() function with anonymous callback
// and delay in milliseconds.
setTimeout(() => {
  console.log(alert);
}, 5000);
8. Untuk menjadwalkan eksekusi callback yang berulang, gunakan
node timers.js
3 Penting untuk dipahami bahwa fase polling pada kenyataannya mengontrol kapan setiap callback pengatur waktu dijalankan karena kode yang lambat dapat memblokir eksekusi. Waktu tunda yang diteruskan ke fungsi pengatur waktu adalah waktu minimum yang akan dilewati sebelum panggilan balik dieksekusi. Akhirnya, penghitung waktu tak terbatas perlu dihapus atau tidak direferensikan, jika tidak maka akan terus berjalan hingga proses selesai dengan callback keluar

Apakah baik menggunakan setInterval dalam JavaScript?

Fungsi setInterval() biasanya digunakan untuk menyetel penundaan fungsi yang dijalankan berulang kali, seperti animasi . Anda dapat membatalkan interval menggunakan clearInterval(). Jika Anda ingin fungsi Anda dipanggil sekali setelah penundaan yang ditentukan, gunakan setTimeout().

Apakah setInterval sebuah lingkaran?

setInterval() sederhananya, adalah putaran waktu .

Bagaimana fungsi setInterval () bekerja di JavaScript?

JavaScript setInterval() metode. Metode setInterval() dalam JavaScript digunakan untuk mengulang fungsi tertentu pada setiap interval waktu tertentu. Ini mengevaluasi ekspresi atau memanggil fungsi pada interval tertentu. Metode ini melanjutkan pemanggilan fungsi hingga jendela ditutup atau metode clearInterval() dipanggil

Apa yang bisa saya gunakan selain setInterval?

Panggilan setTimeout bersarang adalah alternatif yang lebih fleksibel untuk setInterval , memungkinkan kita menyetel waktu antar eksekusi dengan lebih tepat. Penjadwalan tanpa penundaan dengan setTimeout(func, 0) (sama seperti setTimeout(func) ) digunakan untuk menjadwalkan panggilan "sesegera mungkin, tetapi setelah skrip saat ini selesai".