How can I activate a Timeout function once I have assigned it an ID?

Suppose I assign an ID to a JavaScript setTimeout function, what would be the proper way to activate or fire it?

var timerId = setTimeout(function(){alert('doh')}, 1000);
//timerId; doesn't work, 
//execute it here
clearTimeout(timerId)

Answer №1

Executing the setTimeout() function will trigger the desired action. To have this action repeated every second, you should consider using setInterval() instead:

var timerId = setInterval(function(){alert('oops')}, 1000);
// An alert will pop up every second until clearTimeout(timerId) is executed.

It seems that calling clearTimeout() right after setTimeout() might be why you're not seeing the alert message as anticipated.


On another note, it's advisable to refrain from using the alert() function for debugging purposes due to its blocking nature. Instead, opt for console.log() which allows non-blocking execution and enables easy inspection of variables.

Answer №2

The main purpose of the return value from setTimeout is for canceling the timer, which can also be achieved using clearTimeout.

If you need to trigger the timer earlier than scheduled, you can simply clear it and then call the original function.

Here's an example:

function doh(){
    alert('doh')
}

var timerId = setTimeout(doh, 1000);
clearTimeout(timerId)
doh();

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

The state in a functional component in React fails to update after the initial axios call

Issue : The value of "detectLanguageKey" only updates after selecting the language from the dropdown twice. Even after selecting an option from the dropdown for the first time, the detectLanguageKey remains empty and is only updated on the second selectio ...

Tips for utilizing $http and $location in custom directives

I'm completely new to working with Angular, and I have a simple question about using $http and $location in directives. I'm trying to create a task list and would like to be able to delete an entry when clicking on a link. Right now, I've a ...

Removing and shattering data from a JSON file at a designated location in AngularJS

I have received json data that is structured like this (and unfortunately cannot be modified): Desc: First data - Second data My current method of displaying this data involves using the following code: <div ng-repeat="b in a.Items">{{b.Desc}}< ...

Nextjs throws an error indicating that the element type is invalid when an object is passed into the export function

Currently, I am in the process of developing a blog page and facing an issue while attempting to pass generic data stored in an object inside an array. The specific error message I am encountering is "Error: Element type is invalid: expected a string (for ...

In an effort to organize a roster of student roll numbers for the class, I am utilizing a JavaScript function to generate and update an array with the most recent entries

Greetings! I am looking to enhance the functionality of my webpage by allowing users to input the name and roll number of a new student. Once submitted, I want to add this student to an existing list using Javascript functions, for loops, and arrays, and d ...

Transferring a large volume of JSON objects to a database using API post requests

Currently, I'm faced with the challenge of sending a large amount of JSON objects to a database through API post calls. However, upon attempting to send all these objects individually, I encounter numerous HTTP errors, predominantly 400 errors. My in ...

Encountering issues with loading styles in Vue single file components

While working on my project at this link, I encountered an issue with displaying a styled modal. Despite trying to import the styles using: <style scoped> @import "../styles/modal-style.css"; </style> and even directly pasting the co ...

Angular 2's Multi-select dropdown feature allows users to select multiple options

Recently, I encountered an issue with customizing CSS for angular2-multiselect-dropdown. I found the solution in this link: https://www.npmjs.com/package/angular2-multiselect-dropdown. I have included my code below. Any assistance in resolving this matter ...

Step-by-step guide on how to configure the URL path in an AJAX function call

How can I dynamically set the URL path in an AJAX function call when clicking on a page so that the page name is included in the URL? For example, if I click on a particular page (let's say the "ask" page on Stack Overflow), the URL should look like: ...

Using Vuex: Bypassing Action and triggering Mutation directly within Component

When working with a vue.js app and utilizing vuex as the state management store, one may need to update a property's value in vuex. This can be achieved through two methods: One can dispatch an action method, which will then commit a mutation to a ...

In Javascript, develop a function that takes in two arguments and output a two-dimensional array

I am looking to create a function that takes two arguments, rows and columns. The goal of this function is to generate a 2D array with the specified numbers and rows provided as input. Below is the code snippet for implementing this: Feedback from seasone ...

Using dynamic, deferred loading of scripts in JavaScript

Is it necessary to create a reference for a dynamic, lazy import that is used multiple times in a script? For example, if there are 2 event handlers importing different functions from the same module: /* index.js */ window.addEventListener("click", (e) =&g ...

The fullcalendar function 'refetchEvents' does not initiate a request for new data

Here is the code snippet you can refer to: Whenever I modify the selection in the "eventSelect" dropdown menu, it consistently triggers the following post request: POST: http://example.com/events.php end: 2017-02-25 start: 2017-02-20 state: all I am ...

Ways to eliminate nested properties in JSON.stringify()

Looking to make alterations to a string using Typescript. The string is generated by the JSON.stringify() function. I aim to eliminate the attributes "id", "lightStatus", and "value" from both "inputPort" and "outputPort" objects, only keeping their respe ...

An alert box displays N times when the submit button is clicked N times

Consider the following function: function validateForm() { var elements = ["firstname", "lastname", "password", "favfood", "favsport"]; document.getElementById('register').setAttribute('noValidate', true); document.getElement ...

The <base href> element leads to the display of an "[$rootScope:infdig] " error

I am attempting to pass two parameters from first.html to second.html through the URL and retrieve the values in second.html using routeParams. The base tag has been set as <base href="file:///D:/abhilash/node/angapp/"/> and upon clicking a button, t ...

Angular 1.5.0 - What is the reason for factory being invoked only once?

I am facing an issue with my html template where the data from an Angular factory is only loaded once when the page initially loads. Subsequent page openings show the same results from the first backend call, indicating a potential caching issue within the ...

Submit multiple forms using dojo's xhrGET method

I am searching for a solution on how to use ajax to submit multiple forms in one xhr.post call using dojo. The documentation mentioned below at the end of this page states: Actually, the attribute "form:" can be set on any node, not just form nodes. I ...

What steps are involved in importing remark-gfm into next.config.js?

I am interested in incorporating MDX into next.js with the remark-gfm plugin. After discovering the Next.js Docs on MDX, I decided to follow their guidelines and added an import statement. // next.config.js import remarkGfm from 'remark-gfm;' co ...

Using Javascript outside of the AngularJS environment

I am trying to utilize Javascript functions outside the controller in Angular JS instead of using a service within a module. Is this allowed? For instance: var UrlPath="http://www.w3schools.com//angular//customers.php" //this section will store all the f ...