Using setInterval as a counter - javascript

I'm trying to create a page that changes every 10 seconds 4 times and then begins again. To do this I made a counter and passed it along with my function. It doesn't even seem like its loading.
I tried using <body onload="start()"> as well.
<script>
var i = 1;
function start(){
i = setInterval(changeEdu, 10000, i);
}
function changeEdu(i){
if(i == 4){
i = 1;
}else{
i++;
}
document.getElementById("edu1").src = "left" + i + ".jpg";
document.getElementById("edu2").src = "right" + i + ".jpg";
return i;
}
</script>

By declaring i as a parameter of your function, your increment will only mutate the local variable and not your global state. Also the return value is ignored.
var i = 1;
function start() {
setInterval(changeEdu, 10000);
}
function changeEdu() {
// ^^
if (i == 4) {
i = 1;
} else {
i++;
}
document.getElementById("edu1").src = "left" + i + ".jpg";
document.getElementById("edu2").src = "right" + i + ".jpg";
}

I believe it is because you are reassigning variable i at the onset of the start() function. setInterval returns a number that is used to cancel the function with the clearInterval(theNumber) function.
I am also quite new to JS, but I would try to delete the reassignment in the start() function and try again.

That is not how setInterval works, it doesn't return your return value.
You need to create a closure.
Also, your startInterval() is never called.
Change it to this and it works:
<script>
(function(){
var i = 1;
function changeEdu(){
if(i == 4){
i = 1;
}else{
i++;
}
// document.getElementById("edu1").src = "left" + i + ".jpg";
// document.getElementById("edu2").src = "right" + i + ".jpg";
console.log(i);
}
setInterval(changeEdu, 10000);
})();
</script>

Related

setInterval function not stopping but runs infinitely

Please check this on :
http://jsfiddle.net/wmaokqh3/
<div id="message">
</div>
<audio id="bgm" src="http://www.freesfx.co.uk/rx2/mp3s/9/10780_1381246351.mp3">
</audio>
<div id="count">
</div>
function Typer() {
var dfd = $.Deferred();
var srcText = 'EXAMPLE';
var i = -(1);
var result = '';
setInterval(function() {
if (i == srcText.length) {
clearInterval(this);
dfd.resolve();
};
$("#count").append('<br>i =' + i + ' , ');
i++;
result += srcText[i].replace("\n", "<br />");
$("#message").html(result + '---' + i + ' , ');
},
1000);
return dfd.promise();
}
function playBGM() {
var playsound = $.Deferred();
$('#bgm')[0].play();
$("#bgm").on("ended", function() {
playsound.resolve();
});
return playsound.promise();
}
function thirdFunction() {
alert('third function');
}
Typer().then(playBGM).then(thirdFunction);
Not sure where you learned to do clearInterval(this) but that is not correct. The this has nothing to do with the current interval. You need to use the generated id for the interval to cancel it.
var myInterval = window.setInterval( )
and in your code you need to use that id
clearInterval(myInterval)
You have to assign the setInterval to a variable in order to clear it later:
var result = '';
const myInterval = setInterval(function() {
if (i == srcText.length) {
clearInterval(myInterval);
So there is nothing in coding clearInterval(this)
clearInterval function needs a variable in the paranthesis in order to give it a variable you should set the interval function into a variable which should be like this var inter = window.setInterval(function() {}, 1000);

How to break from Jquery click callback function

I am making my own version of simon Game, but the callback function inside click is not existing after user press wrong input. As a result function handler.patternRepeatPlayer() is getting called recursively for each element of array pattern.I want a solution to break from the else after callinghandler.patternRepeatPlayer just once. The program is working fine in strict mode, but only in non-strict mode inside else , I am not able to break from else.
-- can access the project on Git.
https://github.com/santosh1357/simonGame.git
The flow is like from html -> Function simonnGame.PatternGen from PatternGen -> handler.PatternRepeatPlayer -> PatternRepPlayer -> PatternMatcher -> userInput(here if wrong user input in non-strict mode) -> patternRepeatPlayer
This case is failing as in this case else is not existing after calling the function only once.
//Problematic Function.
userInput: function(){
var userPattern = new Array();var id;
$('img').click(function(){
id = parseInt(this.id,10); userPattern.push(id);handler.effect(id);
if(userPattern.indexOf(id) !== simonGame.PATTERN.indexOf(id)){
if($('.chkStrict:checked').val() === "on"){
var audio = new Audio('sounds/wrong.mp3');
audio.play();
setTimeout(function(){window.location.reload(true)},1000);
} else {
var audio = new Audio('sounds/wrong.mp3');
audio.play();
userPattern.length = 0;
handler.repeatFlag = true;
handler.patternRepeatPlayer(); ****//this is getting called recursivelly rather than quiting after calling once****
return ;
}
}
//End Problematic Functiom
I think there is some misunderstanding on how click callback functions work.
//Fullcode
var simonGame = {
COUNT: 0,
PATTERN: [],
SOUND:[{file:'sounds/sa.mp3'},{file:'sounds/re.mp3'},{file:'sounds/ga.mp3'},{file:'sounds/ma.mp3'},{file:'sounds/pa.mp3'},{file:'sounds/dha.mp3'},{file:'sounds/nee.mp3'}],
patternGen: function(){
var randomId;
randomId = Math.floor(Math.random() * 7);
simonGame.PATTERN.push(randomId);
if(simonGame.COUNT > 20){
alert("You have won the game!!");
window.location.reload(true);
}
simonGame.COUNT += 1;
//debugger;
//console.log("increase count true calling count display " + simonGame.COUNT);
handler.countDisplay();
//console.log("count gen true calling patternPlayer with PATTERN " + simonGame.PATTERN );
handler.patternRepeatPlayer();
}, //close patternGen
patternMatcher: function(genPattern){
//console.log("inside patternMatch");
var genPattern = simonGame.patternGen;
//setTimeout(function(){
//console.log("PATEERN: " + simonGame.PATTERN + "COUNT " + simonGame.COUNT );
//calling user input
console.log("calling user Input");
handler.userInput();
setTimeout(function(){
if(handler.repeatFlag === false){ //execute count gen only if repeat flag is false inside user INPUT
genPattern();
}
},simonGame.COUNT*2000);
//console.log("pattern check true, calling pattern gen");
//},simonGame.COUNT*5000); //c`enter code here`lose setTimeout
}, //close patternMatcher
} //close simonGame
var handler = {
countRepPlayer: 0,
repeatFlag: false,
patternRepeatPlayer: function(){
var repeater = setInterval(function(){
handler.effect(simonGame.PATTERN[handler.countRepPlayer]);
handler.countRepPlayer += 1;
if(handler.countRepPlayer > simonGame.COUNT){
clearInterval(repeater);
//setTimeout(function(){
simonGame.patternMatcher();
//},1000);
handler.countRepPlayer = 0;
}
},1000);//close sestInterval
}, //close patternRepeatPlayer
effect: function(id){
var img = document.getElementById(id);
if(img !== null && id !== undefined){
$( img ).fadeIn(100).fadeOut(100).fadeIn(100);//fadeOut(200).fadeIn(200);
//debugger;
var audio = new Audio(simonGame.SOUND[id].file);
audio.play();
//console.log("id inside effect " + id)
}
},//close effect
countDisplay: function(){
document.getElementById("count").innerHTML = "Count: " + simonGame.COUNT;
}, //close countIncrease
userInput: function(){
var userPattern = new Array();var id;
$('img').click(function(){
id = parseInt(this.id,10);
userPattern.push(id);
handler.effect(id);
console.log(" user " + userPattern);
console.log(" pattern " + simonGame.PATTERN);
if(userPattern.indexOf(id) !== simonGame.PATTERN.indexOf(id)){
console.log(" WRONG USER INPUT ");
if($('.chkStrict:checked').val() === "on"){
var audio = new Audio('sounds/wrong.mp3');
audio.play();
setTimeout(function(){window.location.reload(true)},1000);
} else {
console.log("inside else " );
var audio = new Audio('sounds/wrong.mp3');
audio.play();
userPattern.length = 0;
handler.repeatFlag = true;
handler.patternRepeatPlayer(); ****//this is getting called recursivelly rather than quiting after calling once**.**
return ;
}
}
//reset the userPattern Array
if(userPattern.length === simonGame.PATTERN.length){
userPattern.length = 0;
}
}); //close click.
}
} //close handler
Yes, It will be called recursively, because you set interval for it.
Here you can modify your code:
patternRepeatPlayer: function(){
var repeater = setInterval(function(){
handler.effect(simonGame.PATTERN[handler.countRepPlayer]);
handler.countRepPlayer += 1;
if(handler.countRepPlayer > simonGame.COUNT){
clearInterval(repeater);
//setTimeout(function(){
simonGame.patternMatcher();
//},1000);
handler.countRepPlayer = 0;
}
},1000);//close sestInterval
}
To: (EDITED)
function myCallbackFunction(repeater){
handler.effect(simonGame.PATTERN[handler.countRepPlayer]);
handler.countRepPlayer += 1;
if(handler.countRepPlayer > simonGame.COUNT){
clearInterval(repeater);
simonGame.patternMatcher();
handler.countRepPlayer = 0;
}
}
patternRepeatPlayer: function(){
var repeater = setInterval(function() {myCallbackFunction(repeater);}, 1000);
}
And where you need to call it once, just call myCallbackFunction(repeater)

I can't use my function in Javascript

I'm getting error with my function change_slide().
ReferenceError: change_slide is not defined on line 24:1.
My code is here:
$(document).ready(function() {
function change_slide() {
number = pclass.charAt(6);
number = parseInt(number);
if (number == 5) number = 1;
else number++;
$('.picks').removeClass(pclass);
pclass = 'bgpick' + number;
$('.picks').addClass(pclass);
}
var random = Math.floor((Math.random() * 5) + 1);
var pclass = 'bgpick' + random;
var number;
$('.picks').addClass(pclass);
setInterval('change_slide()', 3000);
$('.next').on('click', function() {
change_slide();
});
});
change_slide() on click .next works, in setInterval doesn't work.
When you use a character string argument to setInterval, the Javascript code is executed in the global environment. You should pass a function reference instead of a character string, then it will be evaluated in the local environment.
setInterval(change_slide, 3000);
Note that you should not put parentheses after change_slide here. That will call the function immediately, instead of passing a reference to the function.
Take the function declaration out of document ready function,
Also change
setInterval('change_slide()', 3000);
To
setInterval(change_slide, 3000);
Here is modified code
$(document).ready(function() {
var random = Math.floor((Math.random() * 5) + 1);
var pclass = 'bgpick' + random;
var number;
$('.picks').addClass(pclass);
setInterval(change_slide, 3000);
$('.next').on('click', function() {
change_slide();
});
});
function change_slide() {
number = pclass.charAt(6);
number = parseInt(number);
if (number == 5) number = 1;
else number++;
$('.picks').removeClass(pclass);
pclass = 'bgpick' + number;
$('.picks').addClass(pclass);
}

setTimeout and setInterval

I want to make this counter starts working within 5 seconds of being on the page, but I can not link the setTimeout with setInterval , you would know how could I?
Try to wrap your interval with the setTimeout function:
// interval variable
var cycle = 10;
// variable for the interval since we are invoking it within a function, the callMeEverySecond function can't reach it
var t;
var callMeEverySecond = function() {
cycle--;
// Logs the Date to the console
console.log(new Date());
if(cycle === 0) {
console.log("stop this");
clearInterval(t);
// do something further.
}
}
// Start the timeout after 5 seconds
setTimeout(function() {
// call the function 'callMeEverySecond' each second
t = setInterval(callMeEverySecond, 1000);
}, 5000);
http://devdocs.io/dom/window.settimeout
And a small tutorial: http://javascript.info/tutorial/settimeout-setinterval
Is this ok
var tiempoInicial = 10;
function tiempo() {
document.getElementById('contador').innerHTML='Puedes continuar en ' + tiempoInicial + ' segundos.';
if(tiempoInicial==0) {
clearInterval(t);
document.getElementById("contador").innerHTML = "<p id=\"forumulario\" onclick=\"goToForm1()\">Continuar</p>";
}
}
function iniciar() {
var t = setInterval(tiempo,1000);
clearTimeout(ini);
}
var ini = setTimeout(iniciar, 5000);
Sorry, I tried out the code above and it didn't work so I changed it a bit.
This is the new code.
var tiempoInicial = 10;
function tiempo() {
document.getElementById('contador').innerHTML='Puedes continuar en ' + tiempoInicial + ' segundos.';
tiempoInicial--;
if(tiempoInicial < -1) {
clearInterval(t);
document.getElementById("contador").innerHTML = "<p id=\"forumulario\" onclick=\'goToForm1()\'>Continuar</p>";
}
}
function iniciar() {
t = setInterval(tiempo,1000);
clearTimeout(ini);
}
var ini = setTimeout(iniciar, 5000);

setTimeout() method won't execute

I have written a script, but i want to limit execution time for some functions. I decided to try setTimeout() method, however it results in no time out when i execute the program, i.e. setTimeout() does not work.
setTimeout(rollDice(), 6000) is the line that executes instantly
Here is my code :
function rollDice() {
diceOne = Math.round(5 * Math.random() + 1);
diceTwo = Math.round(5 * Math.random() + 1);
}
function mainFunction() {
playerAI.playing = true;
playerOne.playing = true;
currentScore = 0;
playerAI.totalScore = 0;
playerOne.totalScore = 0;
while (playerAI.playing == true && playerOne.playing == true) {
makeMove();
}
}
function makeMove() {
if (who == 0) {
aiStrat();
game();
}
else {
var confirmAction = confirm("Kas soovite visata täringuid?");
if (confirmAction) {
decision = 1;
}
else {
decision = -1;
}
game();
}
}
function game() {
if (decision == 1) {
setTimeout(rollDice(), 6000); // <--- THIS GETS EXECUTED INSTANTLY
if (diceOne != 1 && diceTwo != 1){
currentScore += diceOne + diceTwo;
//and so on
The code should look like this:
setTimeout(rollDice, 6000);
By adding the parentheses, you're calling the function and setting a timer for calling whatever that function returns. You'll want to pass the function object itself.
You can't immediately use diceOne and diceTwo after setting the timeout. You have to put that code in the timeout function as well, for example:
setTimeout(function() {
rollDice();
if (diceOne != 1 && diceTwo != 1){
currentScore += diceOne + diceTwo;
...
}, 6000);
That's because the code after setTimeout will not wait before the timeout has finished.
Try this:
setTimeout(function(){
rollDice()
}, 6000)
There is no need of Brackets when calling rollDice Function.
setTimeout(rollDice, 6000);
I would use something like this:
setTimeout(function(){rollDice()}, 6000);

Categories

Resources