Argument for setInterval function

As a newcomer to programming, I am attempting to develop a basic javascript game.

I have encountered an issue with the window.setInterval function and it seems to be causing everything to malfunction.

I have been following a tutorial at this link and attempted to modify the code while using different variable names. The original code works perfectly, but when I add the final 3 lines of javascript, the entire project becomes unresponsive. Despite spending 30 minutes reviewing the code, I cannot pinpoint the problem.

main.js

var things = 0;
var gen1 = 0;

function thingClick(number) {
    things = things + number;
    document.getElementById("things").innerHTML = things;
}

function buyGen1() {
    var gen1Cost = Math.floor(10 * Math.pow(1.1, gen1));
    if(things >= gen1Cost) {
        gen1 = gen1 + 1;
        things = things - gen1Cost;
        document.getElementById('gen1').innerHTML = gen1;
        document.getElementById('things').innerHTML = things;
    }
    var nextCost = Math.floor(10 * Math.pow(1.1, gen1));
    document.getElementById('gen1Cost').innerHTML = nextCost;
}

window.setInterval(function) {
    thingClick(gen1);
}

index.html

<!DOCTYPE html>
<html lang="en>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>

<link href="css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="js/main.js"></script>
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->

<body>
Things: <span id="things">0</span><br><br>
<button onClick="thingClick(1)">Get Things</button><br><br>
<button onClick="buyGen1()">Buy Generator Lvl. 1</button><br><br>
Generators Lvl. 1:<span id="gen1">0</span> | Cost:<span id="gen1Cost">10</span>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>

Answer №1

setInterval functions in the following manner:

var interval = setInterval(function(){
  //execute code at regular intervals
},delay)

An illustrative example is as follows:

var interval = setInterval(function(){
   actionClick(gen1);
},2000) //execute every 2000 milliseconds, or 2 seconds

Therefore, your usage of setInterval was incorrect.

You can also halt the interval by clearing it. Thus, in the aforementioned example, simply running clearInterval(interval) will cease it/clear it.

Answer №2

Code Structure

If your JavaScript code contains a syntax error, the execution will halt. It is crucial to pay attention to the structure of your code:

window.setInterval(function) {
    thingClick(gen1);
}

The correct syntax should be:

window.setInterval(function () {
}, 500); // Adjust the interval time as needed


Execution Flow

Imagine the compiler processing steps similar to this:

  • It checks the usage of window.setInterval() with the argument function.
    • If there's any invalid syntax, the compiler throws an error, stopping further execution of JavaScript.
  • If the compiler were to proceed without being halted, it would encounter random code within {}, leading to confusion.


Stopping Intervals

When setting intervals in JavaScript, always assign them to a variable for easy termination. Avoid letting timers run uncontrollably:

var my_timer = window.setInterval(function () {
    thingClick(gen1);
}, 1000); // Set to repeat every 1000 milliseconds

To stop the interval execution, call:

window.clearInterval(my_timer);

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

Tips for effectively closing div elements

How can I modify this accordion to close when a user clicks on another link, and also change the image of the open "p" tag? Currently, clicking on a link toggles the content and changes the image. However, what I am struggling with is closing the previousl ...

Enhanced coding experience with JavaScript completion and ArangoDB module management

Exploring New Horizons After more than a decade of using Eclipse for Java development, I have decided to delve into the realms of javascript and arangodb due to high demand. My current task involves developing multiple microservices to run within arangodb ...

Utilizing API data sharing across AngularJS controllers

I am facing a challenge with my parent controller and its children controllers, as I want them all to share the data fetched from an Api service. Controllers: var app = angular.module('mymodule',[]); app.controller('main', ['$scop ...

Execute a function on a canvas timer using the setTimeout method

I'm having an issue with my setTimeout function in this code. I want it to call a timer function for a delay, but it's not working consistently every second. Why is that happening? <head> <script> function timer(sec) { var c = do ...

Jquery cascading menu

I'm currently experiencing difficulties in creating dropdown menus using jquery and css. Below is my HTML code: <nav class="topNav"> <ul> <li> <a href="#menu" class="menu-toggle"><img src ...

Setting a default value in a multi-select dropdown using react-select

I have taken over management of my first React app, and I am facing a seemingly simple change that needs to be made. The modification involves an email signup page where users can select their interests from a multi-select dropdown menu. My task is to mak ...

Attempting to perform recursion on two functions simultaneously may result in one of the functions being undefined

There is a page on my site that clients tend to keep open for long periods of time without refreshing, sometimes over 24 hours. Some of the actions on this page require a valid PHP session, so I created a simple set of functions to check this every 10 minu ...

Enable the feature for users to upload images to a specific folder within the Chrome extension without the need for

I need to implement a feature in my Chrome extension that allows users to upload images directly to a specific folder named "upload" without needing a submit button. <form action="/upload"> <input type="file" name="myimages" accept="image/*"> ...

Encountering a problem with the state error while trying to modify an input field during onChange event

Whenever I pass state down from a parent component, the setState function keeps triggering an error that says setEmail is not a valid function on change event. Is there a simple solution to fix this issue? Every time I type a string into the email input f ...

Exploring Fetch API with Promise.all

I have successfully implemented a functionality that fetches data from two URLs and performs an action only when both requests are successful. However, I am curious if there is a more efficient and succinct way to achieve the same result. Helper functions ...

Add a unique identifier to a table row in a jQuery/AJAX function without the need for a looping structure

My PHP query retrieves client data and generates a table with rows for each client. Each row contains a link with a unique ID attached to it. Clicking on this link triggers an AJAX function based on the client's ID, which opens a modal displaying info ...

What is the functionality of the keydown event?

Whenever the input text value is not empty, I want my .removetext div to be displayed, but it's not working correctly. When I type something after the second character, my .removetext gets hidden, but it shouldn't be hidden when the input is not ...

Creating space between flex items in Slick Carousel with Vue

This is my current Slick Carousel. There are 4 items in a row, and I am looking to insert some margin between each item while maintaining the existing aspect-ratio: 1.3/1; I'm struggling with overriding the classes from vue-slick-carousel. Does any ...

Is there a way to identify when no rows contain specific values in PostgreSQL or node.js and return false?

Here is an example of a table: P Q t f f t f f In SQL, is there a way to return false when querying for t t, but true when querying for t f, f t, or f f? Should this be handled with node.js by first doing a select and then using if-else statements based ...

Sliding the container with a width adjustment and left margin fails to display all images

In the provided HTML code below, there is a functionality to move images horizontally by clicking on buttons: $(document).ready(function() { calculate_width(); $('#moveleft').click(function() { var loga = $('#marki #loga'); ...

Utilizing Google Sheets as a secure, read-only database for Angular applications without the need to make the sheet accessible to the

Seeking a way to utilize Google Sheets document as a read-only database for my Angular application, I have attempted various methods. However, the challenge with all these approaches is that they necessitate public sharing of the Sheet (accessible to anyon ...

Tips for showing user data following form submission to a SQL database using React JS

Hey everyone, I'm currently working on a project that involves user registration and login. Once the users complete these steps, they are required to fill out an additional form which is displayed below. After submitting this form, the data is stored ...

Creating an Angular form that adapts to changing input values

I'm encountering a problem with angular not recognizing the dynamic values from my inputs. My objective is to have angular populate hidden form fields with lat/lon when a user clicks on the map. The user then submits the form, but the data ends up mi ...

What is the best way to utilize window.find for adjusting CSS styles?

Incorporating both AJAX and PHP technologies, I have placed specific text data within a span element located at the bottom of my webpage. Now, my objective is to search this text for a given string. The page consists of multiple checkboxes, with each check ...

Event Triggered Upon Element Addition to DOM: JQuery Livequery Equivalent in Version 1.7

Is it possible to trigger an event when a certain element is added to a page, especially when I am using a Chrome extension and do not control the source page? I have explored the capabilities of JQuery 1.7's on() method, but it seems to focus on spe ...