跳過到頁腳內容
NODE 說明

JavaScript 等待 5 秒鐘(開發者的使用方法)

在JavaScript中,等待特定的時間(例如5秒)是一個常見的需求。 無論您是想延遲操作還是模擬加載狀態,了解如何在JavaScript中實現延遲是同步程式碼中的關鍵。 在本文中,我們將探討在JavaScript中等待5秒的各種方法,並為每種方法提供範例以暫停JavaScript執行。 另外,我們將利用IronPDF for Node.js來創建PDF文件,使用異步函數和設置超時函數。

1. 使用setTimeout()

setTimeout()函數是一個內建的JavaScript函數,能在指定的毫秒延遲後執行指定的函數或程式碼片段。

範例

console.log("Start");

// Schedules a function to be executed after 5000 milliseconds (5 seconds)
setTimeout(() => {
    console.log("Waited for 5 seconds");
}, 5000);

console.log("End");
console.log("Start");

// Schedules a function to be executed after 5000 milliseconds (5 seconds)
setTimeout(() => {
    console.log("Waited for 5 seconds");
}, 5000);

console.log("End");
JAVASCRIPT

在此範例中,setTimeout()函數內的代碼將在延遲5000毫秒(或5秒)後執行。

JavaScript Wait 5 Seconds (How It Works For Developers): 圖1 - 使用JavaScript setTimeout() 函數並等待5000毫秒或5秒的控制台輸出。

2. 使用Promises和async/await

您也可以使用Promises和async/await在JavaScript中創建延遲,也就是所謂的異步代碼。

範例

async function delay() {
    console.log("Start");
    // Creates a promise that resolves after 5000 milliseconds (5 seconds)
    await new Promise(resolve => setTimeout(resolve, 5000));
    console.log("Waited for 5 seconds");
    console.log("End");
}

// Call the async function
delay();
async function delay() {
    console.log("Start");
    // Creates a promise that resolves after 5000 milliseconds (5 seconds)
    await new Promise(resolve => setTimeout(resolve, 5000));
    console.log("Waited for 5 seconds");
    console.log("End");
}

// Call the async function
delay();
JAVASCRIPT

在此範例中,delay()函數使用async/await來使用Promise暫停執行5秒。

JavaScript Wait 5 Seconds (How It Works For Developers): 圖2 - 在Promise中非同步使用JavaScript setTimeout() 函數並等待5000毫秒或5秒的控制台輸出。

3. 使用setInterval()

雖然setInterval()函數通常用於重複操作,但您也可以通過在所需時間後清除interval來創建一次性延遲。

範例

console.log("Start");

let timer = setInterval(() => {
    console.log("Waited for 5 seconds");
    // Clear the interval after the desired delay
    clearInterval(timer);
}, 5000);

console.log("End");
console.log("Start");

let timer = setInterval(() => {
    console.log("Waited for 5 seconds");
    // Clear the interval after the desired delay
    clearInterval(timer);
}, 5000);

console.log("End");
JAVASCRIPT

這裡,setInterval()函數每5秒重複提供的函數,直到我們用clearInterval()函數清除interval。

![JavaScript Wait 5 Seconds (How It Works For Developers): 圖3 - 使用JavaScript setInterval() 方法並等待5000毫秒或5秒的控制台輸出。 . 然後使用clearInterval()函數清除interval】(/static-assets/pdf/blog/javascript-wait-5-seconds/javascript-wait-5-seconds-3.webp)

4. 使用new Promise()

您可以使用new Promise()創建在指定延遲後解析的Promise。

範例

console.log("Start");

// Delay function that returns a promise which resolves after `ms` milliseconds
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// Use the delay function
delay(5000).then(() => {
    console.log("Waited for 5 seconds");
    console.log("End");
});
console.log("Start");

// Delay function that returns a promise which resolves after `ms` milliseconds
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// Use the delay function
delay(5000).then(() => {
    console.log("Waited for 5 seconds");
    console.log("End");
});
JAVASCRIPT

在此範例中,delay()函數返回一個在5秒後解析的Promise,然後我們使用.then()在延遲後執行代碼。

JavaScript Wait 5 Seconds (How It Works For Developers): 圖4 - 使用Promise和JavaScript delay()和then()函數等待5秒的控制台輸出。

5. IronPDF JS簡介

IronPDF JavaScript庫用于PDF生成提供了一個JavaScript庫,使開發人員能夠直接從客戶端JavaScript操縱和生成PDF文件。 它提供了一系列功能,幫助通過JavaScript創建、編輯和轉換PDF文件。

安裝IronPDF JS

要開始使用IronPDF JS,您需要在專案中包含IronPDF JavaScript庫。 您可以通過CDN包含它,或者直接從IronPDF網站下載。

npm install @ironsoftware/ironpdf
npm install @ironsoftware/ironpdf
SHELL

6. 在IronPDF中使用JavaScript等待5秒

現在,讓我們看看在以下代碼片段中我們如何結合JavaScript代碼延遲技術和IronPDF來使用異步JavaScript解譯器創建一個PDF文件,並在等待5秒後使用。

代碼範例

import { PdfDocument } from "@ironsoftware/ironpdf";

(async () => {
    const html = `<html><body><h1>Hello, IronPDF!</h1></body></html>`;
    // Wait for 5 seconds
    await new Promise(resolve => setTimeout(resolve, 5000));
    // Create PDF from the HTML content
    const pdfDocument = await PdfDocument.fromHtml(html);
    // Save the PDF file
    await pdfDocument.saveAs("Waited.pdf");  
    console.log("PDF Created after wait");
})();
import { PdfDocument } from "@ironsoftware/ironpdf";

(async () => {
    const html = `<html><body><h1>Hello, IronPDF!</h1></body></html>`;
    // Wait for 5 seconds
    await new Promise(resolve => setTimeout(resolve, 5000));
    // Create PDF from the HTML content
    const pdfDocument = await PdfDocument.fromHtml(html);
    // Save the PDF file
    await pdfDocument.saveAs("Waited.pdf");  
    console.log("PDF Created after wait");
})();
JAVASCRIPT

在此代碼片段中,async函數使用async/awaitsetTimeout()等待5秒。 延遲之後,使用IronPDF的PdfDocument.fromHtml()方法創建具有簡單HTML內容的新PDF文件。 您可以根據具體需求替換PDF生成代碼,或使用生成的PDF數據進行進一步處理。

![JavaScript Wait 5 Seconds (How It Works For Developers): 圖5 - 使用JavaScript setTimeout() 函數等待5秒的控制台輸出。 然後IronPDF代碼運行以將HTML字符串轉換為PDF文件,並在控制台中顯示"PDF Created after wait"訊息。】(/static-assets/pdf/blog/javascript-wait-5-seconds/javascript-wait-5-seconds-5.webp)

結論

在JavaScript中等待特定時間是開發人員經常遇到的常見任務。 在本文中,我們探討了使用setTimeout()、帶Promises的async/awaitsetInterval()new Promise()以及JavaScript sleep函數等待5秒的各種方法。

此外,我們介紹了使用JavaScript管理PDF文件的IronPDF JS。 欲了解更多代碼範例,請訪問IronPDF Node.js範例

通過理解這些技術和工具,您可以在JavaScript應用中有效實現延遲,並在更複雜的任務(例如生成PDF文件或執行異步操作)中加以利用。 無論您是初學者還是具有經驗的開發人員,牢固掌握這些基礎將提升您的編碼技能,並使您能夠編寫更高效和穩健的JavaScript應用程式。

Darrius Serrant
全棧軟件工程師 (WebOps)

Darrius Serrant 擁有邁阿密大學計算機科學學士學位,目前任職於 Iron Software 的全栈 WebOps 市場營銷工程師。從小就迷上編碼,他認為計算既神秘又可接近,是創意和解決問題的完美媒介。

在 Iron Software,Darrius 喜歡創造新事物,並簡化複雜概念以便於理解。作為我們的駐場開發者之一,他也自願教學生,分享他的專業知識給下一代。

對 Darrius 來說,工作令人滿意因為它被重視且有實際影響。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me