© Khmer Angkor Academy - sophearithput168

Timing Events

សេចក្តីផ្តើម

Timing Events អនុញ្ញាតឱ្យ JavaScript execute code នៅពេលកំណត់។ Methods ពីរគឺ setTimeout() និង setInterval()។

Timing Methods

Methodការពិពណ៌នាឧទាហរណ៍
setTimeout()Execute once after delaysetTimeout(fn, 1000)
clearTimeout()Cancel setTimeoutclearTimeout(id)
setInterval()Execute repeatedlysetInterval(fn, 1000)
clearInterval()Cancel setIntervalclearInterval(id)

setTimeout()

setTimeout(function() {
  console.log("Executed after 3 seconds");
}, 3000);

Execute code ម្តង បន្ទាប់ពីពេលកំណត់


clearTimeout()

let timeoutId = setTimeout(fn, 3000);
clearTimeout(timeoutId);  // Cancel

Cancel setTimeout មុនពេលវា execute


setInterval()

setInterval(function() {
  console.log("Executed every 2 seconds");
}, 2000);

Execute code ម្តងហើយម្តងទៀត


clearInterval()

let intervalId = setInterval(fn, 1000);
clearInterval(intervalId);  // Stop

ឈប់ setInterval


Countdown Timer

let count = 10;
let timer = setInterval(function() {
  console.log(count--);
  if (count < 0) clearInterval(timer);
}, 1000);

បង្កើត countdown timer


Clock Example

setInterval(function() {
  let now = new Date();
  console.log(now.toLocaleTimeString());
}, 1000);

បង្ហាញពេលវេលា real-time


Best Practices

  • តែងតែ clear timers នៅពេលមិនត្រូវការ
  • ប្រើ arrow functions សម្រាប់ cleaner code
  • ជៀសវាង nested timers
  • ពិចារណា requestAnimationFrame() សម្រាប់ animations

សង្ខេប

  • setTimeout() - Execute once after delay
  • clearTimeout() - Cancel setTimeout
  • setInterval() - Execute repeatedly
  • clearInterval() - Stop setInterval
  • Time ជា milliseconds (1000ms = 1 second)