"यदि कोई कर्मचारी अपना काम अच्छी तरह से करना चाहता है, तो उसे पहले अपने औजारों को तेज करना होगा।" - कन्फ्यूशियस, "द एनालेक्ट्स ऑफ कन्फ्यूशियस। लू लिंगगोंग"
मुखपृष्ठ > प्रोग्रामिंग > How Can I Control Timeout Execution and Determine Remaining Time in JavaScript?

How Can I Control Timeout Execution and Determine Remaining Time in JavaScript?

2024-11-08 को प्रकाशित
ब्राउज़ करें:506

How Can I Control Timeout Execution and Determine Remaining Time in JavaScript?

Pausing and Resuming Timeouts in JavaScript

When working with JavaScript, it can be necessary to control the flow of asynchronous operations such as timeouts. Here, we explore ways to pause and resume active timeouts, as well as retrieve the remaining time on the current timeout.

Pausing and Resuming Timeouts

To pause a timeout, you can utilize a wrapper function that intercepts the window.setTimeout call and provides the necessary functionality. The wrapper function, Timer, takes a callback function and a delay as arguments and handles the pausing, resuming, and tracking of the remaining time.

var Timer = function(callback, delay) {
    var timerId, start, remaining = delay;

    this.pause = function() {
        window.clearTimeout(timerId);
        timerId = null;
        remaining -= Date.now() - start;
    };

    this.resume = function() {
        if (timerId) {
            return;
        }

        start = Date.now();
        timerId = window.setTimeout(callback, remaining);
    };

    this.resume();
};

To use this wrapper, instantiate a Timer object and call its pause() and resume() methods as needed.

Retrieving Remaining Time

To obtain the remaining time on the current timeout, one way is to store the start time when the timeout is set and calculate the difference between the current time and the start time when pausing.

var start = Date.now();
var t = setTimeout("dosomething()", 5000);
var remaining = (start + 5000) - Date.now();

However, it's important to note that if the timeout has been paused and resumed, this calculation may not be accurate. In the Timer wrapper function provided earlier, the remaining time is tracked and updated accordingly, providing a more reliable method for retrieving the remaining time.

विज्ञप्ति वक्तव्य यह लेख यहां पुनर्मुद्रित है: 1729595660 यदि कोई उल्लंघन है, तो कृपया इसे हटाने के लिए स्टडी_गोलंग@163.कॉम से संपर्क करें।
नवीनतम ट्यूटोरियल अधिक>

चीनी भाषा का अध्ययन करें

अस्वीकरण: उपलब्ध कराए गए सभी संसाधन आंशिक रूप से इंटरनेट से हैं। यदि आपके कॉपीराइट या अन्य अधिकारों और हितों का कोई उल्लंघन होता है, तो कृपया विस्तृत कारण बताएं और कॉपीराइट या अधिकारों और हितों का प्रमाण प्रदान करें और फिर इसे ईमेल पर भेजें: [email protected] हम इसे आपके लिए यथाशीघ्र संभालेंगे।

Copyright© 2022 湘ICP备2022001581号-3