comprehending the concept of automatic refreshing of a webpage using javascript

Can someone help me decipher the following code snippet?

function setIdle(cb, seconds) {
        var timer; 
        var interval = seconds * 1000;
        function refresh() {
            clearInterval(timer);
            timer = setTimeout(cb, interval);
        };
        $(document).on('keypress, click', refresh);
        refresh();
    }
    
    setIdle(function() {
        location.href = location.href;
    }, 5);
    

The setIdle function takes two arguments. It contains a nested function called refresh which resets a timer on a scheduled event. Each time an event like click or keypress occurs, the refresh() function is triggered.

At the end of the code block, another call to setIdle is made with a different function and a value of 5, specifying the duration of the timer in seconds. This new function sets the page to automatically refresh (location.href = location.href;) every 5 seconds.

In case I add an additional function:

setIdle(function() {
        console.log('hi');
    }, 1);
    

Why does this second function execute only once instead of every second as the previous one?

Answer №1

setIdle function doesn't continuously run the callback every 5 seconds. Instead, it runs the callback once after 5 seconds of idle time. If there is any user activity such as typing or clicking, the timeout is reset and the callback will not execute until another 5 seconds of idle time have passed.

The reason for the page refreshing every 5 seconds is due to the callback function reloading the page. When the page reloads, all the Javascript on the page is executed again, including calling setIdle() which restarts the process.

However, if you use setIdle a second time without reloading the page, it will only log "hi" once as expected.

If you need something to occur repeatedly at intervals, it's better to use setInterval instead of using setTimeout.

Additionally, it's worth mentioning that clearInterval should be used instead of clearTimeout. While they may work interchangeably in most browsers currently, there is no guarantee. For more information, check out Are clearTimeout and clearInterval the same?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Changing the mouse cursor dynamically with Angular programming

What is the recommended approach for changing the mouse cursor programmatically in Angular? For instance: HTML: <div [style.cursor]="cursorStyle">Content goes here</div> or <div [ngStyle]="{ 'cursor': cursorStyle ...

Changing the hover color of an Angular Material MD Button

<div class="non-active" layout layout-align='space-around center'> <md-button ng-click="$ctrl.widget.type = 'chart'; $ctrl.validateForm()" layout='column' ng-class="{selIcon : $ctrl.widget.type == ' ...

JavaScript is used to manipulate XML documents, including those that are labeled as "undefined."

I'm currently developing an interactive game using HTML5 and I have been focusing on storing various data elements, including character abilities, gear stats, and other related information. My approach involves utilizing XML for static content, while ...

Every time I try to convert my HTML to a PDF using jsPDF, some of the content

Within my React App on the client-side, I've implemented a button to generate a PDF using the current HTML content through jsPDF. Rather than utilizing .fromHTML(), I opted for .html() as it preserves the HTML styles during the conversion process. How ...

A tutorial on adjusting camera angles through mouse dragging in Three.js

I have created a unique Rolex cube with varying layers along the "Z axis" and I need to adjust the camera position to preview the geometry accurately. How can I change the camera position by dragging the window and also manipulate individual cone rotations ...

Using Vue: Triggering .focus() on a button click

My journey with vue.js programming started just yesterday, and I'm facing a challenge in setting the focus on a textbox without using the conventional JavaScript method of document.getElementById('myTextBox').focus(). The scenario is that i ...

Is there a way to ensure that the html is saved when using setTimeout in jquery

Attempting to preserve a specific piece of HTML code, which is displayed when hovering over an element. This overlay HTML content is extracted from a DOM template. When moving the mouse cursor away, I aim to retain the overlay HTML content for the curren ...

Bootstrap3 Remote Modal experiencing conflict due to Javascript

Utilizing a bootstrap modal to showcase various tasks with different content but the same format is my current goal. However, I am encountering an issue when attempting to make the textareas editable using JavaScript. The conflict arises when I open and cl ...

Prevent a JavaScript file from resetting when a user refreshes the page

I'm currently developing a desktop application using node.js and electron. My task involves creating a JavaScript file that manages multiple processes, stores them in a dictionary, and ensures that the dictionary content is retained even without any r ...

What is the best way to establish a default search query within the vue-multiselect component?

I have incorporated vue-multiselect into my project. You can find more information about it here. This is a snippet of my template structure: <multiselect v-model="value" :options="options" searchable="true"></multiselect> When I open the mu ...

Tips for activating swf file autoplay on the mobile edition of WordPress

I recently added a swf file to my WordPress page (https://www.pacifictintlv.com/mobile). However, I have noticed that it does not seem to work properly when viewed on mobile devices. Is there a way to redirect users to the Flash download link if they do ...

Guide on transferring a file to Node.js using FormData and receiving a confirmation response from Node

Hello, I'm currently working on a basic form where I'm attempting to send a file to my Nodejs server using the FormData object. However, I'm facing an issue as my Node server does not seem to receive the file. Additionally, I would like to k ...

Encountering an issue with the node.js express server when fetching data

I'm running into an issue with the fetch function and node.js. When a button is clicked on my frontend, I want to send a post request to receive an array from my backend as a response. My backend is built using node.js with express, and I'm using ...

Using JavaScript to filter through a nested array of objects

I'm having trouble filtering a nested array of objects. Could someone please point out where I might be making a mistake? Here is the data, and I want to filter out all objects that have a risk of P1 { "title": "QA", ...

The confirm() function shows up before the background on a blank layout

I'm facing an issue where whenever my confirm() function pops up, the alert box displays correctly but then the background turns blank. I've tried various solutions like moving the entire if statement to the bottom of the page or at the end of th ...

Performing double string splitting with multiple separators in javascript

If I have a string like a.b.c.d#.e.f.g.h#.i.j.k.l and want to split it first by "#" and then by ".": str = a.b.c.d#.e.f.g.h#.i.j.k.l res = str.split("#") res[0] will contain a.b.c.d after the first split. Now, I need to further split this data. Is th ...

How to access vue.js 3 single file component functions from within a script tag

Imagine having a single file component structured like this: <template> // content irrelevant </template> <script> export default { data() { return { redLocations: [ "Isfahaan", "Qom", ...

Issues with basic routing in Angular version 1 are causing problems

I'm encountering an issue while setting up my first Angular app with routing. It seems to be a simple problem but it's not working properly. Whenever I click on the links, the URL changes. index.html - file:///C:/Users/me/repos/angularRouteTes ...

Monitor the scrolling progress across four separate HTML pages without the percentage decreasing when scrolling back up

I am in the process of developing an e-learning platform and I would like to include a scrolling indicator that visually represents the progress of pages read. The website consists of four HTML pages, with each page corresponding to 25% of the scroll bar. ...

Accordion jQuery failing to display tabs

I have a question about using 2 jQuery accordions with tabs inside them. Everything seems to be working, but when I try to expand the second accordion, the two tabs inside don't render properly. I'm not sure what the issue is. Any help on this wo ...