Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีส่งพารามิเตอร์ให้ setTimeout() Callback ใน JavaScript

ส่ง argument ให้ callback ของ setTimeout() ได้โดยตรงในพารามิเตอร์ที่ 3 ขึ้นไป (รองรับในเบราว์เซอร์สมัยใหม่ทุกตัว)

ไวยากรณ์

setTimeout(functionName, milliseconds, arg1, arg2, arg3...)

ตัวอย่างจากบทความต้นฉบับ

<!DOCTYPE html>
<html>
  <body>
    <button onclick="timeFunction()">Submit</button>
    <script>
      function timeFunction() {
        setTimeout(function(){ alert("After 5 seconds!"); }, 5000);
      }
    </script>
    <p>คลิกปุ่มด้านบนและรอ 5 วินาที</p>
  </body>
</html>

ตัวอย่างส่งพารามิเตอร์จริง

function greet(name, age) {
  console.log(`Hello ${name}, you are ${age} years old`);
}

// ส่งพารามิเตอร์โดยตรง (Modern browsers)
setTimeout(greet, 1000, 'John', 25); // หลัง 1 วินาที: Hello John, you are 25 years old

วิธีเก่า (สำหรับ IE9 หรือเก่ากว่า)

// ใช้ anonymous function wrapper
setTimeout(function() {
  greet('John', 25);
}, 1000);

// หรือใช้ bind
setTimeout(greet.bind(null, 'John', 25), 1000);

ตัวอย่างเพิ่มเติม

1. ส่ง Object/Array

function processUser(user) {
  console.log('Processing:', user.name);
}

setTimeout(processUser, 2000, { name: 'Alice', role: 'admin' });

2. ใช้กับ Arrow Function

const notify = (message, type) => console.log(`[${type}] ${message}`);

setTimeout(notify, 3000, 'Operation completed', 'success');

3. Cancel Timeout

const timeoutId = setTimeout(greet, 5000, 'John');

// ยกเลิกก่อนถึงเวลา
clearTimeout(timeoutId);

ข้อสังเกตสำคัญ

  • พารามิเตอร์เพิ่มเติมรองรับใน IE10+, ทุกเบราว์เซอร์สมัยใหม่
  • ไม่รองรับใน IE9 และเก่ากว่า → ใช้ wrapper function หรือ bind
  • this context จะเป็น window (หรือ undefined ใน strict mode) → ใช้ arrow function หรือ bind

เปรียบเทียบ setTimeout vs setInterval

คุณสมบัติsetTimeoutsetInterval
รันครั้งเดียวซ้ำๆ ตาม interval
หยุดด้วยclearTimeout(id)clearInterval(id)
ส่ง param ได้ได้ (param ที่ 3+)ได้ (param ที่ 3+)