execute a task automatically for a designated duration of time

I have a specific task that needs to be executed for a defined period of time. Currently, I am utilizing the set interval function, but I require a dynamic timeout period fetched from a database. In the getInactiveTimePeriod function, I retrieve the time from browser local storage as a result of an API call. The time is in milliseconds, just as expected. Here is my code:

<script>
var timeInMilliseconds;
window.setInterval(function() {
       getInactiveTimePeriod();
 } , 10000);

 function getInactiveTimePeriod() {
  chrome.storage.local.get("user_inactive_time", function (obj) {
     var timeInMinuts = obj.user_inactive_time;
     timeInMilliseconds = timeInMinuts * 60000;

});
 }
 getInactiveTimePeriod();
 checkUserInactivity();

 function checkUserInactivity() {
    setTimeout(function () {
       // code
   }, timeInMilliseconds);
 }
 checkUserInactivity();
</script>

However, this function only runs once. I need assistance in resolving this issue.

Answer №1

Start by retrieving the value from the database and then utilize setTimeout function to proceed. Follow this approach:

<script>
window.setInterval(() => {
    getInactiveTimePeriod(); //this function will run every 10 seconds
}, 10000);

function getInactiveTimePeriod() {
    var timeInMilliseconds = $valueFromDatabase; // retrieve time value from database
    //using arrow functions for a single scope
    setTimeout(() => { 
        // your code here
    }, timeInMilliseconds); //execution will be delayed based on timeInMilliseconds value
}
</script>

This method should provide assistance

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

Building a versatile and interactive table using AngularJS with data sourced from a

I am currently working on creating a dynamic table using Angular JS to display data received from a Spring Rest Service. Here is the code snippet I have been working with: // JavaScript Document var app = angular.module("SDLC", []); app.config([&apos ...

ASP.NET MVC controller encountering internal server error 500 during Ajax request

I have a scenario where I need to populate two dropdowns in a view: <select class="input-sm form-control input-s-sm inline" onchange="loadCities()" id="comboState"> ... </select> <select class="input-sm form-control input-s-sm inline" ...

Is the use of 'use client' always necessary in order to utilize a hook in Next.js?

Is it necessary to include 'use client' in every page that uses useSelector when working with Redux in Next.js? If I don't include 'use client', I encounter this error: - error node_modules\react-redux\lib\component ...

Enhancing d3 pie chart with additional information when hovering over slices

I'm currently working on finding a way to display additional text on a pie chart using mouseover in addition to just the data bound to the pie. Here is the code I have implemented: function Pie(value,names){ svg.selectAll("g.arc").remove() var oute ...

Navigate array in vue-chart.js

I've been utilizing Vue-chartjs with Laravel 5.7 for my project. The goal: I aim to pass an array to Vue so that I can dynamically generate a chart by looping through specific values. My approach so far: Here's the array I'm working with ...

Guide to reducing the file size of your JavaScript code in Visual Studio Code

Does anyone have any recommendations for a Visual Studio Code plugin that can automatically minify JS files upon saving? I'm looking for a way to streamline the minification process. ...

I encountered an error while attempting to lint my code because ESLint was not configured to ignore the

Trying to set up eslint in a Next.js project, here is the file structure: .eslintignore .eslintrc.js .next .prettierrc .stylelintrc.js components forms modals modules node_modules In my .eslintignore file, I have added node_modules/*. When running eslint ...

Troubleshooting Problems with Node.js and MongoDB Integration during the .save() Process

Welcome to my sample website, powered by a basic Node.js server. I have managed to set up user creation and posting functionalities successfully. However, there seems to be an issue with saving user data to the database as the saved user object cannot be l ...

Creating a Gulpfile.js that efficiently manages a multitude of files spread across various folders

For my ongoing WordPress projects, I am simultaneously working on themes and plugins. In my theme folder, I have a gulpfile.js that compiles .scss files into .css. I am considering creating a central "master" gulpfile in the root folder to compile .scss fi ...

Vue.js is experiencing an issue with undefined values within computed properties

I have a specific input tag with the model selectedProp: <input type="text" v-model="selectedProp" /> and I need to loop through items in this manner: <div v-for="item of filteredItems">{{item.prop}}</div> Below is the code snippet fo ...

Encountering the error message "Cannot GET /" when trying to access the front page using Express.js

I am a beginner in Node.js. I have been learning through videos and documentation, and I started developing a site following an MVC structure. The node server appears to be working fine, but I am facing an issue where the front end displays 'Cannot GE ...

Ways to showcase a list in 3 columns on larger screens and 1 column on smaller screens

When viewing on a computer, my list appears like this: https://i.sstatic.net/fNhaP.png However, when I switch to a phone, only the first column is visible and the list does not continue in a single column format. I am utilizing Bootstrap for my layout, a ...

What is the reason for Chrome allowing the preflight OPTIONS request of an authenticated CORS request to function, while Firefox does not?

As I develop a JavaScript client to be integrated into third-party websites, similar to the Facebook Like button, I encounter a challenge. The client needs to access information from an API that requires basic HTTP authentication. Here is how the setup is ...

Tips for designing the microphone appearance on the Google Chrome speech input interface

Google Chrome features an input control for speech recognition. If you want to know how to use it, check out this link. I'm looking to enlarge the microphone icon and possibly use a customized image for it. Increasing the width and height of the inp ...

Turn off drag and drop functionality and activate selection in HTML

Recently, I encountered a strange issue where selected text became draggable and droppable onto other text, causing it to concatenate. To resolve this problem, I added the following code: ondragstart="return false" onmousedown="return false" However, thi ...

The "next" button on my carousel is unresponsive and the automatic transitioning feature is not working

I'm having trouble implementing a carousel on my website. The next/previous buttons and automatic slides are not functioning properly. <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <!- ...

Can anyone clarify what the term 'this' is referring to in this particular snippet of code?

Upon analyzing the following code snippet: export abstract class CustomError extends Error { abstract statusCode: number; constructor(message: string) { super(message); Object.setPrototypeOf(this, CustomError.prototype); } abstract seri ...

JQuery .click function functioning properly on alternate clicks

Currently, I am integrating JQuery with ReactJS. However, there seems to be an issue where the action that should occur when clicking a button only works on every other click. The first click doesn't trigger anything, but the second one does. I attem ...

byte sequence displays as binary data (angular + express)

I've been working on pulling files from a back-end Node.js / Express server and displaying them in an Angular front-end. Despite trying different methods, I keep facing the same issue - the data displayed at the front-end appears as a bytestring. Even ...

"Attempting to connect to REST server using angularjs $resource. Unexpectedly, the success callback does not

After attempting to set up a REST server on Nodejs and accessing it from AngularJS using $resource for the first time, I have encountered some issues... In my controller, I am trying to load a JSON object (shopping cart) upon login for existing users or c ...