Initiating, halting, and rejuvenating a timer in JavaScript

Here is a simple code snippet where I'm experimenting with starting, stopping, and resetting a JavaScript timer.

The goal is to have a timer running on a page that sends a message once it reaches the end of its countdown before restarting. The stop button should halt the timer indefinitely.

The code in the provided fiddle achieves this functionality, but I am unsure if I am approaching it correctly. Is using setTimeout the most effective way to create such a timer, or would setInterval be better?

Additionally, my current reset function looks like this:

var onReset = function() {
        clearTimeout(timerHandle);
        onStart();    
};

Is there a more elegant method to reset a timer in JavaScript?

Any insights are appreciated!

Answer №1

If you want to improve your code, consider encapsulating it all in an object. Let me know if you need an example. Alternatively, you can keep the existing structure and simply update your onStart function as shown below to eliminate some unnecessary code:

var onStart = function() {

    timerHandle = setInterval(function() {
        $("#console").append("timer fired.. <br />");
    }, 2000);

};

Check out this fiddle for a demonstration: http://jsfiddle.net/qx6CM/

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

Assigning a variable within a parent function from a child function in JavaScript

Struggling to assign the value of "result" in the inner function. Any suggestions on how to do this? I am able to console log the result variable inside the function, but a friend recommended using promises. However, I have no clue how to implement that ...

Is there a way to store a JSON object retrieved from a promise object into a global variable?

var mongoose = require('mongoose'); var Schema = mongoose.Schema; const NewsAPI = require('newsapi'); const { response } = require('express'); const newsapi = new NewsAPI('87ca7d4d4f92458a8d8e1a5dcee3f590'); var cu ...

Has Chrome's console disappeared?

After reinstalling Chrome and opening the dev tools with F12, I encountered an error with the following code: console.debug('test'); The error message displayed was Uncaught ReferenceError: console is not defined(…) This issue persisted acro ...

Tips for utilizing both the Element Selector and Class Selector in Jquery

I am working with a simple table that has TDs assigned either the 'PLUS' or 'MINUS' class. My goal is to use jQuery to implement functionality for collapsing all or expanding all. When the Expand All button is clicked, I need to chang ...

Is it possible to incorporate FCM into Next.js and effectively handle server-side events for FCM on Next.js servers?

Is it feasible to incorporate the Firebase Cloud Messaging (FCM) into my upcoming Next.js application? Can I manage both client-side and server-side modules within the server side? ...

Transform the column's datetime into a date in the where condition when using sequelize

Hey there, I'm looking to convert a datetime column into just date format while running a query. Could someone assist me with creating a Sequelize query based on the example below? select * from ev_events where DATE(event_date) <= '2016-10- ...

MongoDB Client > Error: No operations provided - cannot proceed

NPM Library: "mongodb": "3.1.4" Encountering an issue while attempting to bulk insert a list of data: Here is the code snippet: db.collection('products').insertManyAsync(products, {ordered: false}) The error message displayed: An Invalid O ...

underscore's _.each() method for callback functions

I've been struggling with implementing my custom _.each() function within another function and keep encountering the issue of getting "undefined" returned. My goal is to utilize _.each() to apply a test function to an array. Despite being aware that t ...

Tips for linking together AJAX requests with vanilla JavaScript

I have searched extensively for solutions using only plain JavaScript, but I have not been able to find a suitable answer. How can I tackle this issue with pure JavaScript given that my repetitive attempts haven't yielded any results? function ...

Error in Access-Control-Allow-Origin when using Node.js and JSONP

It seems like JSONP eliminates cross domain restrictions. I am currently attempting to create a JSONP service with node and express. Below is a simple example of the code: self.routes['/portfolio'] = function(req, res) { // Website you wis ...

Using command line arguments to pass parameters to package.json

"scripts": { "start": "gulp", ... }, I have a specific npm package that I'm using which requires passing parameters to the start command. Can anyone help me with how to pass these parameters in the command line? For example, is it possible ...

Having trouble with accessing properties like `d3.svg()`, `d3.scale()` and other features of d3js within an Angular 2 environment

Struggling to incorporate d3.js into angular2. Below is the command I used to install d3 in Angular2: npm install --save d3 install --save-dev @types/d3 This is how my package.json appears: { "name": "my-app", "version": "0.0.0", "license": "M ...

Having trouble sending an array with res.send() in NodeJS

My User model contains a field that stores an array of course IDs like this: "courseId" : [ "5ac1fe64cfdda22c9c27f264", "5ac207d5794f2910a04cc9fa", "5ac207d5794f2910a04cc9fa" ] Here is how my routes are set up: router.get('/:userid/vendo ...

Sending a POST request in nodeJs that does not return any value

I have a button on my client site that sends a POST request to my server. The request does not require a response as it simply inserts data into the database. However, after clicking the button, the client continues to wait for a response until it times ou ...

Interrupting one process and initiating a new one

Trying to create a simple animation using Velocity.js. This animation will transition between two looping states upon clicking an svg. The first state involves horizontal scaling from scaleX(1) to scaleX(2.5) and back to scaleX(1), while maintaining scaleY ...

Escaping double quotes in dynamic string content in Javascript can prevent unexpected identifier errors

Need help with binding the login user's name from a portal to a JavaScript variable. The user's name sometimes contains either single or double quotes. I am facing an issue where my JavaScript code is unable to read strings with double quotes. ...

Tips for inserting information into data tables

Let me begin by outlining the process I am undertaking. I interact with a remote JSON API to retrieve data, perform some basic operations on it, and ultimately produce a data row consisting of three variables: Date, name, and message (think of an IRC chat ...

Access an HTML file in Text Edit on a Mac directly from a web browser

Is there a way to utilize Javascript or another appropriate script to open an HTML file in Text Edit on my Mac? I have created a local web page using Text Edit that has different tabs linking to other Text Edit files within the page. I am looking for a m ...

How do I adjust brightness and contrast filters on a base64 URL?

When presented with an image in base64 format like this: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDAAwfqNRk/rjcYX+PxrV/wtWqwJSTlboMgAAAABJRU5ErkJggg== What is the most efficient method to programmatically alter a filter (such as brightness or cont ...

Using Node.js to download files with like wget, unzip them, and convert them to JavaScript without saving to

Currently, I am working on a script for a nodejs/express server-side application using the libraries request, unzip, and xml2js. The goal of this script is to fetch a zip file from a specified URL, extract an XML file from it, and then parse that XML into ...