Showing a series of JavaScript countdowns consecutively

I am working on a project where I want to display a second countdown after the first one finishes using meteor. The initial timer code looks like this:

sec = 5
@timer = setInterval((->
  $('#timer').text sec--
  if sec == -1
    $('#timer').fadeOut 'fast'
    sec=
    timer
  return
), 1000)

This is how I trigger it: When the template is rendered, I use setTimeout to start the countdown.

Template.selector.rendered = ->
  window.setTimeout(startGame, 5000)
  timer

Upon starting the game, I need a second countdown. I implemented it as follows:

sec = 5
sw = 0
@timer = setInterval((->
  $('#timer').text sec--
  if sec == -1
    if sw == 0
      sw = 1
      sec = 20
    else if sw == 1
  clearInterval timer
  return
), 1000)

However, I believe there must be a more efficient way to achieve this.

Answer №1

If you want to manage multiple timers efficiently, consider creating a custom object for that purpose. Take inspiration from the following code snippet found on this GitHub repository. You can customize it further based on your specific requirements by utilizing custom events:

ReactiveTimer = (function () {

    // Constructor
    function ReactiveTimer(interval) {
        this._dependency = new Tracker.Dependency;
        this._intervalId = null;

        if(_.isFinite(interval))
            this.start(interval);

    };

    ReactiveTimer.prototype.start = function(interval){
        var _this = this;

        this._intervalId = Meteor.setInterval(function(){
            // rerun every "interval"
            _this._dependency.changed();
        }, 1000 * interval);
    };

    ReactiveTimer.prototype.stop = function(){
        Meteor.clearInterval(this._intervalId);
        this._intervalId = null;
    };

    ReactiveTimer.prototype.tick = function(){
        this._dependency.depend();
    };

    return ReactiveTimer;
})();

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

Top choice for removing items from a list array

Hey there, I'm working with an array of a custom type in Angular: List { task: string; id?: number; status?: boolean; } I'm trying to figure out how to delete elements where List.status == true. I've tried two methods for this. ...

Using Javascript to retrieve form data from a separate file

I am struggling with my HTML and JavaScript files to collect data. Despite my efforts, the function is not executing properly. Below is the code I have been working on: HTML File : <form class="form-newsletter"> <div class="form-group"> ...

Executing Firebase Cloud Functions to perform write operations within a database event function

Exploring the world of Firebase functions has been an exciting learning journey for me. This innovative feature is proving to be incredibly powerful and beneficial. I'm eager to utilize a function that can capture a database writing event, perform a ...

I encountered a console issue that I am struggling with. It is showing the error message "TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'"

When running this code, I encountered an error in the console (TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'). Can someone help me identify where I made a mistake and provide guidance ...

Leveraging JavaScript event handlers within a progress wizard located within an update panel

I need assistance with implementing a password strength meter for a textbox within a wizard control. The issue I'm facing is that the password box does not become visible until step 4, preventing me from registering an event handler onload(). Placing ...

RecoilRoot from RecoilJS cannot be accessed within a ThreeJS Canvas

Looking for some guidance here. I'm relatively new to RecoilJS so if I'm overlooking something obvious, please point it out. I'm currently working on managing the state of 3D objects in a scene using RecoilJS Atoms. I have an atom set up to ...

The function os.platform in React and Electron mistakenly identifies the browser as the operating system instead of the actual OS

In my quest to locate the appdata folder for the application, I encountered a challenge where each operating system has a different path for the appdata or application support folder. To address this, I attempted to identify the OS type in order to deter ...

The Navbar's Toggle Icon Causes Automatic Window Resize

I implemented a mobile navigation bar using React and JS that slides in from the left when clicked. However, I encountered two issues: whenever I click on a menu button in the navbar or when my ad carousel moves, the window resizes for some reason. Additio ...

Unique text: "Custom sorting of JavaScript objects in AngularJS using a special JavaScript order

I'm working with an array structured like this: var myArray = []; var item1 = { start: '08:00', end: '09:30' } var item2 = { start: '10:00', end: '11:30' } var item3 = { start: '12:00& ...

Issue accessing object property in Handlebars template with ExpressJs

Personalized Routes: router.use(function(req, res, next) { res.locals.currentUser = req.user; next(); }); /* Accessing the home page. */ router.get('/', function(req, res, next) { console.log(res.locals.currentUser.username); ==>> t ...

Loop through the v-for based on the input number that was selected

I'm looking to accomplish the following: if a user selects input X (a number between 1 and 10), I want to render a specific vue component X times. It seems to work if I use v-for n in 10, but not when I use variables. <template> <div> ...

What is the best way to apply focus to a list element using Javascript?

I recently created code to display a list of elements on my webpage. Additionally, I implemented JavaScript functionality to slice the elements. Initially, my page displays 5 elements and each time a user clicks on the "show more" link, an additional 5 ele ...

Troubleshooting: Heroku Node Version Update Issue

Looking to update the node version of my app deployed on Heroku. Currently, it is running version 0.10.40 on the Heroku app. To switch to the desired version, I made changes to the package.json file as follows: { "name": "myapp", "private": true, " ...

Retrieve the native interface from the Puppeteer browser/page context

Can a native interface be obtained from the Browser or Page instance to verify if an object is an instanceof this interface? For example, in a testing scenario with jest (where CanvasRenderingContext2D is not available due to being a Node context rather t ...

Verify the content of each file in a bulk upload before transferring them to the server

I am facing an issue with a form that has 3 separate file input fields. I need to validate their MIME types individually before uploading them to the server. The first two should only allow MP3 files, while the last one should only allow JPEG files. Is th ...

Maximizing the power of datatables with ajax integration

Exploring pagination with AJAX on datatables.net is something I want to try. I have two input fields where users can enter start and end dates, followed by the table structure below: <table class="table table-hover" id="example"> < ...

Issue with AngularJS Cross-Origin Resource Sharing (CORS) when making HTTP requests, whereas standard Ajax and jQuery are

I'm currently dealing with a straightforward cross-domain service that is set up to handle Simple CORS requests. When I try to access it using a plain xmlHTTP call or jQuery($.ajax), everything works smoothly. However, when attempting to make the call ...

"Retrieve an image source using a jQuery Ajax call and swap it on

I am working on a webpage that includes an <img src="..." /> tag with a default src set. My goal is to use jQuery to make an ajax request to fetch another image, and only once this new image has fully loaded, update the src attribute of the <img ...

Selecting a particular item in a list depending on time using JavaScript, jQuery, or Angular

When working with a JSON file and binding it to list items, I have included a name/value pair in the json for each line indicating audio time, such as "time like 0, 5, 10 in seconds form". In my Cordova application, I am using a media plugin and implement ...

Tips on how to remove the filter from a select element using Angular?

My code includes the following HTML: <select ng-options="mark.id as mark.name for mark in marks" ng-model="markSearch.mark.id"> <option value="">-- Choose mark --</option> </select> ... <tr ng-repeat-start="pipeType in pipeT ...