I am having trouble with setInterval not functioning as expected. I am trying to make a function repeat every 500ms using setInterval, but it seems to be ineffective

var direction;
function movement(){
    switch(direction){
        case 1: positionX = positionX + 10;
                break;
        case 2: positionX = positionX - 10;
                break;
        case 3: positionY = positionY - 10;
                break;
        case 4: positionY = positionY + 10;
                break;
    }
    snake.style.marginLeft = positionX + "px";
    snake.style.marginTop = positionY + "px";
}

function changeDirection(a){
    direction = a;
}

setInterval(movement(), 500);

I am facing an issue with the setInterval function not working as expected in my JavaScript code. I have tried different ways to call the function including writing just the function name, using funcName, and funcName() but none seem to make it work.

Answer №1

setInterval expects a callback as its first argument, not the result of a function call.
Instead of:

setInterval(movement(), 500);

try using:

setInterval(movement, 500);

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

Obtaining an address using latitudes and longitudes with React Google Maps

I created a map using the react-google-map plugin where users can drag the marker to get the latitude and longitude of a location. However, I am only able to retrieve the lat and lng values and not the address. How can I obtain the address as well? Take a ...

Tips on identifying HTML email input validation using JavaScript?

Just like when you can determine whether an input element with a required attribute was successfully validated, try using the following code: if($('input[type="email"]').val() && $('input[type="email"]').val().includes('@') & ...

Traverse JSON data using associative loops

Is there a way for me to iterate through this JSON data without using numerical indexes? I want to treat it like an associative array. This is what I have so far: $.post('/controlpanel/search', { type: type, string: string }, function(data){ ...

Storing a dynamically created grid of inputs using a consistent ng-model

I have the following code snippets: $scope.createPack = function(informationsPack, informationsActivite) { PackService.add(informationsPack, informationsActivite) .then(function(res) { $state.go(&apos ...

Refreshing a div using ajax technology

I am attempting to use Ajax to update an h3 element with the id data. The Ajax call is making a get request to fetch data from an API, but for some reason, the HTML content is not getting updated. This is how the JSON data looks: {ticker: "TEST", Price: 7 ...

It appears that Javascript variables are behaving in a static manner

I am currently building a PHP website with a registration page for users. I am implementing the LOOPJ jQuery Autocomplete script from to enable users to select their country easily. In this process, I encountered an issue where the value of another field ...

The supertest request body cannot be found

Testing my express server POST endpoint using supertest has been a challenge for me. Although everything works perfectly in postman, I encountered an issue when trying to pass body parameters into the test. It seems like the body parameters are not being p ...

`To activate/deactivate tabs by choosing options from drop-down menus`

Hey there, I'm currently dealing with a combo box that has 5 drop down items in Tab1. There are also other tabs present such as tab2, tab3, tab4, and tab5. Tab1 is enabled while the other tabs are disabled. Each of the disabled tabs contains different ...

jquery plugin for creating Excel-like filters

I am in the process of creating Excel-like filtering for my dynamic table. To achieve this, I am utilizing a jQuery plugin that can be found at https://github.com/chestercharles/excel-bootstrap-table-filter. The reason why I chose this plugin is because it ...

What is the best method for disabling autoscroll for a specific div id when the :target attribute

I created this accordion menu using only html and css, but the buttons are built with the :target id. Is there a way to prevent the automatic scrolling when any button is clicked without using javascript? It currently moves to the anchor #id. I've se ...

What is the best method to assign the value of a useState variable to a specific field in an array of objects for inserting data in

**I have a billing form that includes product details for the admin to fill out. One field, labeled "BillID", should automatically populate with a default value of 'Bill ID + 1' through a variable. **Below is the code: const [BillIdFetch, setB ...

Uploading files with Angular and NodeJS

I am attempting to achieve the following: When a client submits a form, they include their CV AngularJS sends all the form data (including CV) to the Node server Node then saves the CV on the server However, I am encountering difficulties with this proc ...

Jasmine attempting to access a nonexistent property

I created a very basic component: import { Component } from '@angular/core'; @Component({ selector: 'loading', templateUrl: './loading.component.html', styleUrls: ['./loading.component.scss'] }) export ...

Utilizing Angular.js to extract data from a deeply nested array of objects in JSON

Hello, I am currently learning about Angular.js and working on developing a shopping cart. In this project, I need to display an image, name, and cost of each product for multiple tenants. Each tenant has an array called listOfBinaries which contains listO ...

What is the process for running child_process when a user clicks on a view in an application

Just starting out with Node.js and utilizing express along with hogan or moustache templating for my views. I've successfully used the following code in my routing files, index.js as shown below: /* Test Shell Execute. */ router.get('/shell&apo ...

Error arises when using ODBC PDO alongside Ajax functionality

I've encountered a problem while working on a project at my job. I'm using PDO queries and ajax to generate dynamic elements, but I can't seem to fix a specific issue. The problem is that regardless of the option selected in two dynamically ...

Whenever a user logs in or logs out from the child component, the app.js is not being re-rendered

I'm having trouble figuring out how to re-render the app.js function. It loads initially, but when I click the login or logout button, I need to call a function from the helper again to check the user status. Here is the code snippet for App.js: impor ...

Utilize Google Chrome Developer Tools to interact with the "Follow" buttons on the webpage by clicking on them

https://i.stack.imgur.com/W32te.png Here is the script I am currently using: document.querySelectorAll('.components-button components-button-size-mini components-button-type-orange desktop components-button-inline').forEach(btn => btn.click() ...

What is the correct way to declare this and assign values afterwards? (javascript)

I am having trouble with this code and I can't figure out how to properly declare it. var input = { container: '.slide_container', container_all: '.slide_show', slides: [] }; var $slides = $(&a ...

Ways to get to the bottom in a React component using a button

I've been struggling to automatically scroll the user to the bottom of the page when they click on a button. Despite my best efforts, I haven't been able to find a solution. Can someone please assist me in achieving this goal? Thank you ...