What is the best way to continuously loop an image from left to right and right to left indefinitely using JavaScript?

As part of the challenge, I am tasked with creating a Pacman game using HTML, CSS, and JavaScript. One key aspect is to control the movement of the ghosts throughout the game. However, I am facing an issue with the current function that controls the ghost's movement - it only gets called once, causing the ghost to stop. Is there a way to make this function run continuously for an infinite amount of time?

function moveEnemy() {
        var e1 = document.getElementById("e1");
                if(parseInt(e1.style.left)>10 && parseInt(e1.style.left)<1000)
                    e1.style.left = parseInt(e1.style.left) + 5 + 'px';
                else if(parseInt(e1.style.left)<10 && parseInt(e1.style.top)<500)
                    e1.style.top = parseInt(e1.style.top) + 5 + 'px';
                else if(parseInt(e1.style.left)<10 && parseInt(e1.style.top)>500)
                    e1.style.top = parseInt(e1.style.top) - 5 + 'px';
                else if(parseInt(e1.style.left)>1000 && parseInt(e1.style.top)>500)
                    e1.style.left = parseInt(e1.style.left) - 5 + 'px';

    }

Since I'm unable to utilize jQuery for this task, any solution using pure JS would be greatly appreciated :)

Answer №1

To achieve continuous execution in intervals, you can utilize the setInterval function.

setInterval(moveEnemy, 1000);

By specifying the time interval as 1000, the function moveEnemy will be invoked every second. You can adjust this value to set a different interval for executing the function.

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

Exploring the architecture of Redux-thunk and validating the impact of side effects

I've been using redux-thunk and I'm not entirely sure if my side effects (specifically the showAlertError function) are structured properly. While my jest test setup seems to be fine at first glance, I encountered an error: jest.fn() value mus ...

What is the best way to incorporate text or characters into your website using CSS only, without using

Will it be able to function in IE? I am aware that IE does not support the content property for anything outside of what? ...

Adding an automatically generated link within an HTML form

I am working on a web page that displays dynamic content and includes a form for user submissions. How can I add a unique reference to each of these pages within the form? <div class="detalle-form-wrap"> <div> <h1> ...

Comparing Ajax HTML with XML/JSON responses: which is better for speed or other considerations

I have a website that heavily relies on ajax, and I insert around 3k html formatted pages into the DOM through ajax requests. My current approach involves inserting the entire html responses using jQuery. However, another option is to output in xml or jso ...

What are the implications of an unidentified callback function with parameters?

Check out this snippet: const fs = require('fs'); fs.readFile('foo.txt', 'utf8', (error, data) => { if (error) { throw new Error(error); } console.log(data); }); Can you figure out where the anonymous callback is recei ...

Having trouble getting jQuery click event to work with Express for loading a Handlebars page

My jQuery on click function is not working properly in conjunction with Express to route to a handlebars page and display the passed information. I have attempted different solutions such as changing the HTTP method from GET to POST, not using handlebars ...

The error message "ReferenceError: express is not defined" indicates that Node.js is

Recently, I started using Nodejs to develop web servers, utilizing the express module. To install it, I used the command: "sudo npm install -g express". However, upon running the program, an error occurred: "ReferenceError: express is not defined ...

Python web scraper unable to locate specified Xpath

My question was previously posted here: Xpath pulling number in table but nothing after next span In testing, I successfully located the desired number using an XPath checker plugin in Firefox. The extracted results are displayed below. Although the XPa ...

Utilize PHPMailer to send pre-designed email templates

Apologies for the recurring queries. I'm still struggling to find a solution to this issue. Here's my Query: I have a form that allows users to choose between predefined and custom templates. The select option determines which template is displ ...

The entire title serves as a hyperlink, not just the text portion

Apologies if I'm making mistakes, I'm just starting out with coding and navigating this website. So here's the deal: I am trying to add advertisements to my website on the left and right sides of the centered "Logo" at the top. The issue i ...

"Divs of the same type automatically adjust size to fit within the

I am currently exploring the possibility of creating a versatile component that can be customized based on the needs of its parent element, whether through bootstrap or traditional flexbox / CSS grid. I want to determine the level of reusability this compo ...

Strange issue encountered when utilizing Worklight along with XSL transformation on a JSON response

I'm facing an unusual issue that I can't seem to resolve. Here is an example of a JSON response that I am dealing with. "values": [ { "time": "2014-02-26T09:01:00+01:00", "data": [ "A", "B" ] }, // additional objec ...

Creating input fields in Vue 3: Best practices

I am looking to create an input field that automatically removes entered characters if they do not match a specific pattern. Here is the template: <input type="text" :value="val" @input="input" /> And here is the ...

Extract the element when the mouse is clicked

I'm currently working on developing a Chrome extension with a specific goal in mind: My aim is to capture the username when a user Ctrl-clicks on a username while browsing Reddit, and then transfer that username from the content script page to the ba ...

I was disappointed by the lackluster performance of the DataTable in CodeIgniter; it did not

I recently started using CodeIgniter and I'm having trouble getting the dataTable to work. Here's a snippet of my page: <table class="table table-striped table-bordered table-hover dataTables_default" id="dataTables-example"> ...

<ul><li>issue with indentation

Is there a way to eliminate the indent from my unordered list? While inspecting the element, I noticed what appears to be padding between the width of the box and the content. However, setting padding to 0px and margin to 0px doesn't seem to work as t ...

Is there a way to alter the background color of a Material UI card when it is being hovered over

I'm currently using material ui with react and I have a question regarding the background color of my card component when a user hovers over it. Can someone help me figure out how to achieve this? For reference, here is the live code link in CodeSand ...

Clear out all current cookies

I utilized the following JavaScript code to generate a pop-up window on the website that would only appear once. However, my client now wants to launch a new promotion and I am attempting to remove existing cookies so that the pop-up window displays again ...

Leveraging Vue 3 Composition API with accessors

I'm currently in the process of refactoring some of my components using the composition API. One component is giving me trouble, specifically with asynchronous state when trying to retrieve data from one of its getters. Initially, the component was u ...

Using jQuery to assign the value of a hidden element to data being posted

When using jQuery's post() method to call an ajax action that returns JSON data ({"Success": "true" } or {"Success": "false"}), the value of a hidden HTML element is supposed to be set to the Success value in the returned object. However, after settin ...