Is it the browser's responsibility to track active setInterval
and setTimeout
IDs, or is this solely left up to the developer?
If the browser does keep track of them, can they be accessed through the Browser Object Model (BOM)?
Is it the browser's responsibility to track active setInterval
and setTimeout
IDs, or is this solely left up to the developer?
If the browser does keep track of them, can they be accessed through the Browser Object Model (BOM)?
To keep track of intervals, developers can utilize the returned value from setTimeout/setInterval and pass it to clearTimeout/clearInterval functions, as mentioned in previous responses.
The reason for this is due to each browser handling interval tracking differently.
According to w3.org/TR/2009/WD-html5-20090212/no.html (although a draft version, w3schools and explain it similarly) - setTimeout and setInterval return a long value which can be used with clearTimeout/clearInterval to locate and cancel the interval.
To implement global timer tracking, you can customize the setTimeout
and setInterval
functions. This allows you to easily monitor when a timer is initiated or completed, as well as keep tabs on active and expired timers.
Here's an example:
activeTimers = {}; // store ongoing timers in this object
originalSetTimeout = window.setTimeout;
// redefine `setTimeout` to track all timers
window.setTimeout = function(callback, time) {
var timerId = originalSetTimeout(function() {
console.log(timerId + " has reached its timeout");
delete activeTimers[timerId]; // stop tracking expired timers
callback();
}, time);
// add this timer to the `activeTimers` object
activeTimers[timerId] = {id: timerId, setAt: new Date(), timeout: time};
console.log(timerId + " will expire in " + time + "ms");
}
// From now on, every use of setTimeout will be monitored, logged to the console, and ongoing timers will be stored in the "activeTimers" object.
If you're curious about how the timer is retained within its window, this could be of interest to you.
<!doctype html>
<html lang= "en">
<head>
<meta charset= "utf-8">
<title>Timer </title>
</head>
<body>
<h1>Timers</h1>
<script>
if(!window.timers){
var timers= [], i= 0;
while(i<5){
timers.push(setInterval(function(){
if(confirm(timers.join('\n')+'\nRemove a timer?')){
clearInterval(timers.shift());
}
},
i*1000+1000));
++i;
}
}
</script>
</body>
</html>
Latest Update:
This question has two main components to consider.
It appears that the OP is concerned with whether timer IDs are monitored in a general context, particularly because developers may desire to have control over them.
In essence, yes, timer IDs are indeed tracked by the browser (as pointed out by @s_hewitt, they are stored as long
values) and developers can oversee them by retaining references to the timers upon setup.
Developers have the ability to manage (e.g. halt) these timers by invoking functions such as (clearInterval(handleRef), or clearTimeout(handleRef))
Nevertheless, there isn't a built-in window.timers
collection or similar feature that provides a list of all active timers - this responsibility falls on the developer to maintain such a list if deemed necessary.
function startPolling(delay){
pollHandle = setInterval(doThis, delay);
}
function stopPolling(){
clearInterval(pollHandle);
}
function doThisIn30minUnlessStopped(){
timerHandle = setTimeout(doThisThing, 1800000);
}
function stop30minTimer(){
clearTimeout(timerHandle);
}
All you have to do is establish a variable reference for your timer, and when necessary, clear it using its designated name.
Upon navigating to another page, the browser will automatically clear all existing timers, eliminating the need for manual handles unless specified otherwise.
Take a look at the code snippets provided below, demonstrating how the browser can retain the id for each setTimeout iteration
for (x = 1; x <= y; x++) {
(function(z) {
var interval = z/y;
a[z] = setTimeout(function() {
element.style.left = z+"px";
},interval);
})(x);
}
To access these intervals, you can utilize
for (x in a) {
alert(a[x]);
}
Currently, I am loading data into a bootstrap table on my JSP. The table class is hidden at the moment. After successfully uploading the data into the bootstrap table, I have implemented the following code: $(function() { var table = $('#Table') ...
I have decided to use UserVoice for a free user voting service due to their API, allowing me to create a custom UI, which is essential for my needs. However, it seems that users are unable to upload images along with their suggestions, only text. It is i ...
data.forEach((d, i) => { setTimeout(() => { drawCanvas(canvasRef, d); }, 1000 * i); }); I have implemented a loop on an array using forEach with a one-second delay. Now I am looking to incorporate a pause and resume f ...
I am facing a challenge when trying to highlight multiple words within a sentence. Specifically, I have text data that looks like this: "The furnishing of Ci Suo 's home astonished the visitors: a home of 5 earthen and wooden structures, it has a sit ...
I've noticed that a few of my website pages are loading very slowly. After checking Google inspect (console), it seems like the issue is caused by this error: Uncaught ReferenceError: AdjustIframeHeightOnLoad is not defined. This specific piece of co ...
In my current project, I am experimenting with using SVG in a Typescript page in Gatsby. To achieve this, I decided to utilize the Gatsby plugin called . //gatsby-config.js { resolve: "gatsby-plugin-react-svg", options: { ...
My experience with AJAX is limited, but I am currently working on a project that requires a form to submit data without refreshing the page. The goal is to display the result in a modal window instead. To achieve this functionality, I understand that imple ...
Having trouble calling a webservice from a specific directory within my project. The URL I'm trying to access is "~/RA/WebServiceRAOpen.asmx/OpenedRAlistByBranch" but it's not functioning as expected. $.ajax({ url: "~/RA/WebServiceRAOpe ...
Here is the jQuery structure that I am currently working with: $(document).on('click', '.view-details', function () { $(this).prop("disabled", true); // API call1 // API call2 // API call3 $(this).prop("disabled" ...
Here is an example of what my JSON data structure looks like: { "reportSections": [ { "name": "...", "display": true, "nav": false, "reportGroups": { "reports": [ { "name": "...", "ur ...
Looking to seamlessly incorporate an email signup form from Mailerlite.com into your website? Wondering how you can integrate this functionality with React? In particular, are you curious about the process of integrating the JavaScript code required for t ...
When constructing my MaintainCOCComponent, I include a parameter for the MaintainCOCService which contains the API call method service. export class MaintainCOCComponent { constructor(private maintaincocservice: MaintainCOCService) { } } Using Constr ...
Displayed here is a grid (basic html table) showcasing users with the option to delete a specific user by clicking on the delete link. My typical approach involves: <% foreach (var user in Model.Users) {%> <tr > <td align="right"><% ...
I am currently working with this object structure { "Monday": [ { "morning": [ { "start_time": "02:00", "end_time": "07:3 ...
Having a background in C++ and some knowledge of HTML, CSS, and JavaScript, I am currently working on developing a web application using Node.js and React.js. This application will be accessible through both web browsers and mobile devices. My goal is to ...
How can I automatically log the user_id and method name of every method called within a javascript class without adding logger statements to each method? This would allow me to easily track and grep for individual user activity like in the example below: ...
I inserted this iframe into a webpage <iframe src='http://redbug.redrocksoftware.com.au:80/Pages/chamara.html' style="position:absolute;z-index:1;" ></iframe> The chamara.html page has a button that, when clicked, should cover the c ...
While Vuejs is known for being more effective than jQuery for DOM manipulation and user interactions handling, I am curious about its performance when it comes to remote asynchronous HTTP (Ajax) calls. I'm looking for a specific Vue.js core API that c ...
I'm currently working on implementing a system for selecting Country, State, and City using the jQuery method. However, I've encountered an issue where the load event is fired along with the change() event, causing difficulties in loading the Sta ...
I'm currently developing an application using jQuery and jQuery Mobile. I have a script in the head section that dynamically loads both libraries. However, my body contains a script that relies on jQuery ($) and is unable to access it because it loads ...