javascript object method recursively call [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
My question is related to the play function. How can I call this Player.play() method recursively call?
Using this.player.play() is not working.
function Player(playlist){
open:function(){
//doing some stuff 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())

At first, your syntax is a comvination of a function and a class, you may use a class like:
class Player {
constructor(links,element){
this.images = links;
this.position = 0;
this.element = element;
}
//...
}
Then you can set an Interval that shows one image after another:
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;
}
Now you can do:
var player = new Player(
["1.jpg","2.jpg","3.jpg"],
document.getElementById("img")
);
document
.getElementById("play-btn")
.addEventListener("click", _=>player.play());

If you want to do recursive there should be a stop condition.
this.player.play() is not correct.Should be this.play()

Related

How to rewrite code without the .video element in it? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
How would that be done here? https://jsfiddle.net/bqfv5j06/
Those were the instructions I was given.
Currently, I am telling JavaScript to go find it every time a button
is clicked. This is the equivalent of Googling for the person’s phone
number everyday. It is a waste of time and system resources.
document.querySelectorAll('button.cover').forEach(function(button) {
button.addEventListener('click', function (event) {
document.querySelector('.video').dataset.id = event.target.dataset.id;
});
});
How exactly would this be done?
Me: If I understand you correctly, you are wanting me to rewrite that
code without the .video element included in it?
Do I have that correct?
And the answer I got back was, "Yes"
Your instructor wants you to cache the result of the call once, and then use that cache instead of searching the DOM every time.
const myVideo = document.querySelector('.video');
document.querySelectorAll('button.cover').forEach(function(button) {
button.addEventListener('click', function (event) {
myVideo.dataset.id = event.target.dataset.id;
});
});
If you want to use this with a "standard for loop", you can do this:
const myVideo = document.querySelector('.video');
const buttons = document.querySelectorAll('button.cover');
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function (event) {
myVideo.dataset.id = event.target.dataset.id;
});
}
// or
for (const button of buttons) {
button.addEventListener('click', function (event) {
myVideo.dataset.id = event.target.dataset.id;
});
}

Add function to Object with an element selector [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have an Object
function Object(name, button) {
this.name = name;
this.button = button;
var alert = function () {
alert("x");
};
}
var ExampleOne = new Object('Example One', $('.exampleButton'));
How can I make the function inside the object fire on an event of Object[button]...
Using -
ExampleOne.button.click(function () {
ExampleOne.alert();
});
Doesn't work.
var alert = function is a local function and cannot be accessed outside that object. If you want it to be accessible with new instances, declare it with this:
function Object(name, button) {
this.name = name;
this.button = button;
this.alert = function () {
alert("x");
};
}
Fiddle: http://jsfiddle.net/qow3qu0m/2/
It's working for me. Check your code again. Maybe you forgot to include jQuery?
ExampleOne.button.click(function(e) {
alert('success!');
});
http://codepen.io/anon/pen/yyGpLz

JavaScript Module issue? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Module = (function () {
var Method = function () {
this.doSomething =function () {
return "doSomething";
};
}
return {
Method:Method
};
})();
var value=Module.Method.doSomething;
console.log(value);
New to Javascript, coming from a java background.
Why is value coming back as undefined?
Cheers.
You have to have an object of Method to access the property doSomething, you can achieve it like
Module = (function () {
var Method = function () {
this.doSomething =function () {
return "doSomething";
};
}
return {
Method:Method
};
})();
var value= new Module.Method();
alert(value.doSomething());
you can also approach it like
Module = (function () {
var Method = function () {
this.doSomething =function () {
return "doSomething";
};
}
return {
Method:new Method
};
})();
var value=Module.Method.doSomething();
alert(value);
Use as
var value= new Module.Method().doSomething();
DEMO
Module.Method is a function, apparently designed to be used as a constructor. You're also not calling the function.
var value=new Module.Method().doSomething();
^^^ create an instance of Module.Method
^^^ call the doSomething method of it.

How do I increment the value of a variable by 1 every 3 seconds? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
$(document).ready(function() {
var addTime = function() {
var time = 1;
setInterval((function() {
time = time + 1;
}), 3000);
console.log(time);
};
addTime();
});
Right now, it only outputs 2. What Am I doing wrong?
It is being incremented. But it's printed only once.
try this
$(document).ready(function() {
var addTime = function() {
var time = 1;
setInterval((function() {
time = time + 1;
console.log(time);
}), 3000);
};
addTime();
});
Below javascript function would help you.
window.setInterval("javascript function",milliseconds);
And here is the sample code
var myVar=setInterval(function(){myTimer()},1000);
function myTimer()
{
// code you want to execute
}
You can also refer the Jquery Timer..below is the link
http://jchavannes.com/jquery-timer/demo
Here are the multiple options available
var timer = $.timer(function() {
alert('This message was sent by a timer.');
});
timer.set({ time : 5000, autostart : true });
timer.set(options);
timer.play(reset); // Boolean. Defaults to false.
timer.pause();
timer.stop(); // Pause and resets
timer.toggle(reset); // Boolean. Defaults to false.
timer.once(time); // Number. Defaults to 0.
timer.isActive // Returns true if timer is running
timer.remaining // Remaining time when paused

How to convert setInterval to requestAnimationFrame [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
There is a stackoverflow post by a guy called Gustavo Carvalho that shows how camera/viewport works in a HTML5 game.
All's good except that setInterval is used instead of requestAnimationFrame.
I tried converting to requestAnimationFrame without success :-(
Can somebody pls help? Here's the post:
Simple HTML5 game camera/viewport
Thanks very much!
EDIT: After reviewing the answers below, I came up with this solution:
REPLACE THE FOLLOWING CODE...
// Game Loop
var gameLoop = function(){
update();
draw();
}
// <-- configure play/pause capabilities:
var runningId = -1;
Game.play = function(){
if(runningId == -1){
//Use setInterval instead of requestAnimationFrame for compatibility reason
runningId = setInterval(function(){
gameLoop();
}, INTERVAL);
console.log("play");
}
}
Game.togglePause = function(){
if(runningId == -1){
Game.play();
}
else
{
clearInterval(runningId);
runningId = -1;
console.log("paused");
}
}
// -->
REPLACE WITH THIS ONE...
// Game Loop
var gameLoop = function(){
if(gameStatus == 'play'){
update();
draw();
}
window.requestAnimationFrame(gameLoop);
}
var gameStatus = 'play';
Game.play = function() {
gameLoop();
}
Game.togglePause = function() {
if(gameStatus == 'play'){
gameStatus = 'pause';
console.log(gameStatus);
}
else if(gameStatus == 'pause'){
gameStatus = 'play';
console.log(gameStatus);
}
}
You can modify the following parts of the code to:
/// add a flag as condition for loop
var isPlaying = true;
// Game Loop
function gameLoop(){
update();
draw();
/// incorporate loop here
if (isPlaying)
requstAnimationFrame(gameLoop);
}
And then:
Game.play = function(){
if (!isPlaying){
isPlaying = true; /// enable looping
gameLoop(); /// start loop
console.log("play");
}
}
Game.togglePause = function(){
if(!isPlaying){
Game.play();
}
else
{
isPlaying = false; /// this will terminate loop
console.log("paused");
}
}
Note that for latest versions of Firefox and Chrome the requestAnimationFrame is now unprefixed. For older and other browsers you might need to use a polyfill.
The call to requestAnimationFrame function has to actually provide loop in its first argument, that happens to be a function.
So roughly speaking, do something like this:
function draw() {
// some drawing on a canvas happens here
}
function game_loop() {
var callback = function(t) {
draw();
// loop the whole thing:)
game_loop();
};
window.requestAnimationFrame(callback);
}

Categories