Javascript function repeatedly invokes itself to manipulate an object

I have a query regarding the play function. How do I trigger the Player.play() method recursively? Using this.player.play() does not seem to be effective.

function Player(playlist){
  open:function(){
    //performing some actions here
  }
  play:function(){
    if(picture){
      //document.getElementById("img").src =playlist[n]

    }

  }
}
var player = new Player([link1, link2, link3]);
document.getElementById("play-btn").addEventListener("click", player.play())

Answer №1

Initially, your code structure combines a function and a class. A possible approach could be defining a class like this:

 class ImagePlayer {
   constructor(imageLinks, element){
     this.images = imageLinks;
     this.position = 0;
     this.element = element;
   }
   //...
}

Subsequently, you can implement an Interval method to display images sequentially:

next(){
 this.element.src =  this.images[
    this.position = (this.position + 1) % this.images.length
 ];
}

play(){
 if(!this.interval) this.interval = setInterval(_=>this.next(),1000);
}

stop(){
  clearInterval(this.interval);
  this.interval = null;
}

Finally, you can instantiate the class with image links and element ID, then attach a click event listener to start playing:

 var player = new ImagePlayer(
   ["1.jpg","2.jpg","3.jpg"],
   document.getElementById("img")
 );

 document
   .getElementById("play-btn")
   .addEventListener("click", _=>player.play());

Answer №2

When implementing recursion, it is essential to include a stop condition.

The line of code this.player.play() is incorrect; it should be replaced with this.play().

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

Having trouble with Vue.js not returning HTML elements from methods properly?

I have been attempting to retrieve html elements from a method, and I thought of using v-html for this purpose (not sure if there is a better approach). However, I seem to have encountered an issue with backtick templates and string interpolation. An error ...

POST method error 400 encountered

Whenever I execute my ajax jquery function, I encounter a 400 error Here is my code. All Postman tests pass successfully, but when the web app runs, it fails. I'm not sure if it's a coding issue or something related to HTML5. Can anyone offer as ...

Issue with AJAX MVC HTML: jQuery value is not blocking API call

Upon clicking a button, I am triggering a web API call using AJAX. My form is utilizing JqueryVal for form validations based on my viewmodel data annotations. The issue I am facing is that when I click the "Listo" button in my form, it executes the API ca ...

Why does JSON.parse obscure objects in response body when using Node.js?

Whenever I utilize JSON.parse and output some fetched information with the require module, nested objects are shown as [Object]. For example, consider the following code (currently using Node version 10.15): const request = require("request"); const ur ...

Creating TypeScript declaration file for exporting JavaScript function

I'm a beginner with TypeScript and I want to learn how to create a declaration file for a custom JavaScript function. I attempted to do this, however, I encountered an error stating "Could not find a declaration file for module './main'." Ad ...

Implementing debounce functionality in Angular using CodeMirror

I've tried various approaches and even referred to This Possible Dup Currently utilizing the ng2-codemirror 1.1.3 library with codemirror 5.33.0 interface Simply attempting to add a DebounceTime operator to the change event of the CodeMirror Editor ...

From JSON object to HTML table: converting structured data into a user

I'm currently facing a challenge when trying to iterate through JSON data retrieved from an API and display it in an HTML table. After parsing the original JSON, I accessed its elements as follows: JSON (data retrieved from API): {"PrekesID" ...

Strange visualization using Three.js version R69

Recently, I've been experiencing a strange rendering issue with the latest release of the Three.js library. It seems that there is a lack of depth perception for the torus and sphere in my scene - they appear to be overlapped by the grid, which is not ...

Ways to extract the content from the textarea

Currently, I am working on a project that involves using CKEditor. Within the project, there is a panel with various properties used to create a tooltip. I decided to utilize CKEditor to insert content into the tooltip because it provides an excellent user ...

JavaScript event in Chrome extension triggers a browser notification and allows for modification using a specific method

I am currently developing a Chrome extension that is designed to take specific actions when system notifications appear, with the main goal being to close them automatically. One example of such a notification is the "Restore pages?" prompt: https://i.sta ...

Execute a post request upon clicking with NEXT JS, while also firing off a get request

I'm facing an issue where I need to post and get my data when clicking on the same button (similar to writing and displaying comments). However, whenever I click the button, everything seems to be working fine but a request with a 304 status code star ...

The ins and outs of function returns and callback mechanisms

I'm encountering an issue related to the order of my functions and I can't figure out the reason behind it. When I hover over the call for function_2 inside the first function, VSCode shows me the result as Promise<void>, and the console p ...

Traversing through objects in react.js

Hello there, I'm currently learning React and JavaScript but facing some challenges with a particular task. Let's dive into it! So, imagine I have an array like this: clients = ["Alex", "Jimmy"] and then I proceed to create another array using th ...

Tips for submitting data to the identical ejs view or partial following utilizing res.render get?

Is there a way to display data in my EJS file that is posted after the view has been rendered using res.render()? When I try to use <% date %> in my EJS file, it throws an error saying that date is not defined. This makes sense because the value is s ...

Over time (a few days), the setInterval function causes the react app to become unresponsive

In my React app (Next.js), I have implemented a feature that displays a QR code refreshing every 5 seconds, alongside a clock that updates every second. Additionally, I have integrated a service worker to enable Progressive Web App (PWA) functionality and ...

Printing keys of objects in an array in AngularJS through iteration

Here is an array of objects that I am attempting to iterate in ng-repeat and print keys, but I am facing some challenges. $scope.directivesInfo = [ {"ngRepeat": {"enter": true, "leave": true, "move": true, "add": false, "remove": false}}, {"ngView ...

Guide to comparing the contents of two text fields and highlighting the altered characters using ReactJS

Is there a way to compare the contents of two Material-UI textfields and identify the characters that have changed in both? I came across a similar question, but it was specifically for ReactJS rather than C# Windows Forms: How can you highlight the chara ...

Initiating change notification when utilizing service communication

So I am facing an issue with two unrelated components where I am attempting to establish communication between them using a service and a BehaviorSubject. Despite successfully exchanging data, calling the service from one component does not trigger change ...

Retrieve information from various MongoDB collections

Greetings! I currently have a database with the following collections: db={ "category": [ { "_id": 1, "item": "Cat A", }, { "_id": 2, "item": "Cat B" ...

Changing the Size of a Map using react-simple-maps within a React Application

I'm having difficulties with displaying a France map using react-simple-maps. The issue I'm facing is that the map appears too small despite my efforts to adjust it through CSS, width and height attributes, and by utilizing ZoomableGroup. Unfortu ...