Unchecked box

Is there a way to create a checkbox that triggers a timing event when checked, and then stops the event when unchecked? Currently, it seems like the function continues even after unchecking the box, causing the variable to increment at a faster rate.

Live Example

Check out the JS Code below:

var money = 0;

function moneyMaker(){
    money++;
  document.getElementById('money').innerHTML = money;
}

function doautoMoney(){
    window.setInterval(function(){

        moneyMaker();
        document.form.automoney.click();
        //alert('Auto Saved!');
    }, 1000); 
}

Answer №1

To stop the repeated action when a checkbox is unchecked, you can use the clearInterval() method and replace onclick with onchange for checkboxes.

var money = 0;

function moneyMaker() {
  money++;
  document.getElementById('money').innerHTML = money;
}
var int;

function doautoMoney(chk) {
  if (chk)
    // store the interval reference for clearing the interval
    int = window.setInterval(function() {
      moneyMaker();
      //document.form.automoney.click();
      //alert('Auto Saved!');
    }, 1000);
  else
    clearInterval(int)
}
Money: <span id="money">0</span>
<p>
  <button onclick="moneyMaker(1)">Mine Iron!</button>
  <input type="checkbox" name="automoney" onchange="doautoMoney(this.checked);">

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

Increase the activity in every inquiry

In my Node.js application, I have a file with the following contents: index.js contents: var app = require('express')(); var http = require('http').Server(app); function start(){ var timer = setTimeout(function(){ check() ...

The form does not seem to be updating or refreshing even after an AJAX submission and validation

I have a form set up to submit data to my database using jQuery Validate plugin and ajax. However, I'm encountering an issue where after clicking submit, the form does not clear out. While the data does get updated in the database, I need help figurin ...

Is it possible to use both the filter $select.search and the limitTo $select.infiniteCurrentLimit on a single ui-select field?

I am facing a challenge with my ui-select field which utilizes infinite-scroll functionality due to having a large number of options. However, it becomes cumbersome to scroll down and find the desired option among so many choices. <ui-select-choices ...

Guide on getting a website name from a URL using Javascript

Is there a simple method to extract the site name from a URL string? For example: http://www.mysite.com/mypath/mypage -> www.mysite.com http://mysite.com/mypath/mypage -> mysite.com The JavaScript code runs on the mongodb CLI side, not within ...

Bootstrap arranges checkboxes into three evenly spaced columns and centers them within a form

Having trouble organizing my checkboxes into 3 columns and centering them within the form perfectly. Current layout: Click here for image Desired look: Click here for image HTML: ` <form action="/signup" method="POST" ...

If you want to retrieve the calculated value of a div using jQuery

I have a scenario where I have 3 list items (li) under an unordered list (ul). I am interested in finding the height of these list items, but without explicitly defining their height. So far, when inspecting with Firebug, I noticed that the computed height ...

Using jQuery to highlight the navigation menu when a specific div scrolls into view

I have implemented a side navigation consisting of circular divs. Clicking on one scrolls you to the corresponding .block div, and everything functions correctly. However, I am now curious if it is feasible to highlight the relevant .nav-item div based on ...

The process of including or excluding an item in an array

There are 2 toggle buttons. If the value is true, it will be added to the array, otherwise the element will be removed. data: originality: [] toggles: <toggle id='1' ref='toggleOriginal'> Click </toggle> <toggle id=&apo ...

Converting text/plain form data to JSON using Node.js - step by step guide

I am currently working on a Node.js application to execute a POST call to an API for placing an order. However, the data I receive in our app is in text/plain format and not JSON. This is the current format of the data: TypeOrder=buy Coin=BTC AmountCoin= ...

Can you explain the extent to which JavaScript's setTimeout() and clearTimeout() apply?

Approximately 30 seconds after a page is loaded or reloaded, a pop-up will be displayed under certain conditions. The following code successfully achieves this functionality: jQuery(document).ready(function($) { .......... if (localStorage.getItem ...

Tips for managing array data within cookies, sessions, or local storage using jQuery and ensuring they are stored for a set period of time

Is there a way to save the data from an array into cookies, session, or local storage and then later retrieve it as needed? Additionally, is there a method to ensure that this stored information is only available for a specific period of time? Edit I have ...

ReactJS library encounters "Failed to load PDF file." error intermittently while attempting to view a PDF file

I recently developed a React JS application using create-react-app and decided to incorporate react-pdf for viewing PDF files. However, I've encountered an intermittent issue where the PDF sometimes fails to load. Specifically, when I initially load t ...

Difficulty in toggling the visibility of the react-date-range picker package when selecting a date

I need assistance with a problem I'm facing. I am having trouble hiding and showing the react-date-range picker upon date selection. The issue is related to a package that I am using for date range selection. You can find the package link here - https ...

Tips on preventing duplication of APIs when retrieving data using nextjs

In my code, I have a function that can be called either from server-side rendering or client side: export const getData = async (): Promise<any> => { const response = await fetch(`/data`, { method: 'GET', headers: CONTENT_TYPE_ ...

JS ddsclick is not a defined function

Here is the code snippet I am working with: <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script> <script type="text/javascript" src="<%:ResolveUrl("~/Content/JS/jquery.ddslick.min.js")%>" ></scr ...

Limit the width and height of MUI Popper with a maximum setting

After experimenting with the popper API from MUI, I discovered that it extends beyond my main div. Does anyone have suggestions on how to prevent this overflow? I am looking to increase the height of the popper. Please refer to the code snippet below: con ...

Guide to passing the parent state as a prop to a child component and enabling the child to modify the state

I have a situation where my parent component holds 4 buttons to set a payment state, and I need to pass this state to a text field child component. Additionally, I want the text field to be editable so that the state can also be modified through it. My att ...

Encountered a problem while initiating the HTTP server in a node.js

I'm currently attempting to initiate an HTTP server from my index.js file. After going through The Node Beginner tutorial, I've been encountering errors every time I try to start the server using the provided code: Server.js - var http = re ...

Looping through an array in Vue using v-for and checking for a specific key-value pair

As I dive into my first Vue app, I've encountered a minor setback. Here's my query: How can I iterate through a list of dictionaries in Vue, specifically looping through one dictionary only if it contains a certain value for a given key? Provi ...

Executing multiple click events using JavaScript

I have recently started learning JavaScript and am experimenting with the following script: <script type="text/javascript"> $(document).ready (function() { $('#apply').click(function() { $('#applyinfo').toggle ...