I need my code to run x amount of times and then pause for 30 seconds or so before resuming. Any ideas?
myslidefunction();
var tid = setInterval(myslidefunction, 1000);
function myslidefunction() {
setTimeout(function () {
//do stuff
}, 400);
};
You can keep a run-count, and use normal_duration + 30000 as the setTimeout delay for the X+ 1st time.
var runCount = 0, runsBeforeDelay = 20;
function myslidefunction(){
// .. stuff
runCount++;
var delay = 0;
if(runCount > runsBeforeDelay) {
runCount = 0;
delay = 30000;
}
setTimeout(myslidefunction, 400 + delay);
};
// start it off
setTimeout(myslidefunction, 1000);
var counter = 0;
var mySlideFunction = function(){
/* your "do stuff" code here */
counter++;
if(counter>=10){
counter = 0;
setTimeout(mySlideFunction, 30000);
}else{
setTimeout(mySlideFunction, 1000);
}
}
mySlideFunction();
Related
I can't figure out how to add a restarting timer to my simon game. I know setInterval() and SetTimeout but I can't figure out how to have the timer reset for each level if the level is passed within the first 10 seconds. Do I need an if/else to work and concatenate it to level or userClickPattern? I dont know, I tried it all.
Goal:
Have a 10 second timer that starts .click and if the pattern is completed to move to the next sequence if it is not completed then alert("... ) and restart the game. The timer function is at the bottom. Please help me!!!
var buttonColours = ["red", "blue", "green", "yellow"];
var gamePattern = [];
var userClickedPattern = [];
var started = false;
var level = 0;
$(document).keypress(function() {
if (!started) {
$("#level-title").text("Level " + level);
nextSequence();
started = true;
}
});
$(".btn").click(function() {
var userChosenColour = $(this).attr("id");
userClickedPattern.push(userChosenColour);
playSound(userChosenColour);
animatePress(userChosenColour);
checkAnswer(userClickedPattern.length - 1);
});
function checkAnswer(currentLevel) {
if (gamePattern[currentLevel] === userClickedPattern[currentLevel]) {
console.log("success");
if (userClickedPattern.length === gamePattern.length) {
setTimeout(function() {
nextSequence();
}, 1000);
}
} else {
console.log("wrong");
playSound("wrong");
$("body").addClass("game-over");
setTimeout(function() {
$("body").removeClass("game-over");
}, 200);
$("#level-title").text("Game Over, Press Any Key to Restart");
startOver();
}
}
function nextSequence() {
userClickedPattern = [];
level++;
$("#level-title").text("Level " + level);
var randomNumber = Math.floor(Math.random() * 4);
var randomChosenColour = buttonColours[randomNumber];
gamePattern.push(randomChosenColour);
$("#" + randomChosenColour).fadeIn(100).fadeOut(100).fadeIn(100);
playSound(randomChosenColour);
}
function playSound(name) {
var audio = new Audio("sounds/" + name + ".mp3");
audio.play();
}
function animatePress(currentColor) {
$("#" + currentColor).addClass("pressed");
setTimeout(function() {
$("#" + currentColor).removeClass("pressed");
}, 100);
}
function startOver() {
level = 0;
gamePattern = [];
started = false;
}
function timer() {
alert("Out Of Time Better Luck Next time");
playSound("wrong");
$("#level-title").text("Game Over, Press Any Key to Restart");
startOver();
}
Having a timer is easy with setInterval, which, unlike setTimeout, will continue to execute the handler function with the specified delay until the interval is cleared.
If you wanted the value globally, you could do:
let seconds = 0
let timerInterval
function startTimer() {
timerInterval = setInterval(() => seconds++, 1000)
}
function resetTimer() {
seconds = 0
clearInterval(timerInterval)
}
I am working on knockout js.
In that i have a recursive function which executes a function every minute. for that am using a timer every 60 sec it will execute also same will be reflecting in the UI also.
In my case, if i try to assign or initialize a timer value(observable) which is inside a loop, it doesn't reflecting instead of reflecting it is added to the pipeline and that much time loop is running simultaneously.
In that case i want to kill the loop and again want to restart every time i am changing the timer value.
timerInSec=60;
var loop = function () {
if (this.timer() < 1) {
myFunction()
this.timer(this.timerInSec - 1);
setTimeout(loop, 1000);
} else {
this.timer(this.timer() - 1);
setTimeout(loop, 1000);
}
};
loop();
Here is my solution. Please check.
timerInSec = 60;
const Loop = (function () {
let timer = 0;
let timerId = -1;
const myFunction = function () {
console.log('finished');
}
const fnLog = function (tm) {
console.log('current time = ', tm);
}
const fnProc = function () {
timerId = setTimeout(myFunction, 1000 * timer);
}
return {
start: function (tm = 60) {
this.stop();
timer = tm;
fnProc();
},
stop: function () {
if (timerId !== -1) {
clearTimeout(timerId);
timerId = -1;
}
}
}
})();
Loop.start(timerInSec);
setTimeout(() => {
Loop.start(timerInSec);
}, 500);
I have a simple javascript function that loads on document ready:
var start = 1;
var speed = 1000;
$(document).ready(function () {
go();
setInterval(function () {
go();
}, speed);
This is the function in details:
function go() {
$("#score").html(start.toLocaleString());
start += 1;
}
This is basically a counter which starts from number 1 to infinite, at 1000 milliseconds speed. Here is the thing , now: I have another function:
function modify() {
speed = 500;
}
which regulates the setIntval speed on the main function. The problem is it applies on page refresh only. How do I update it in real time without refreshing page?
You can't update the current one, you have to stop it and set a new timer, which does the same but with a different delay.
var speed = 1000;
var start = 1;
function go() {
$("#score").html(start.toLocaleString());
start += 1;
}
function startGoTimer(){
return = setInterval(function () {
go();
}, speed);
}
function modifyTimer( previousTimer, newDelay=500) {
clearInterval(previousTimer);
speed = newDelay;
startGoTimer();
}
var timer = startGoTimer();
// Some code
modifyTimer(timer, 500);
For fun I just tested what would hapopen if you just change the time:
var timing = 1000;
var interval = setInterval(function(){console.log("test")}, timing);
// Now we get a log every 1000ms, change the var after some time (via console):
timing = 10;
// still an interval of 1000ms.
A really simple solution is to make use of the setInterval's parameters,
var intervalID = scope.setInterval(func, delay[, param1, param2, ...]);
and also pass the speed as param1.
Then, at each interval, check if it changed, and if, clear the existing timer and fire up a new.
Stack snippet
var start = 1;
var speed = 1000;
var timer;
$(document).ready(function() {
go();
timer = setInterval(function(p) {
go(p);
}, speed, speed);
// for this demo
$("button").click(function(){ speed = speed/2});
})
function go(p) {
if(p && p != speed) {
clearInterval(timer);
timer = setInterval(function(p) {
go(p);
}, speed, speed);
}
$("#score").html(start.toLocaleString());
start += 1;
}
div {
display: inline-block;
width: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="score">0</div>
<button>Modify</button>
I use this script:
var i = 0;
async.whilst(
// test to perform next iteration
function() { return i <= Myobject.length-1; },
function(innerCallback){
//Some calculations....
setTimeout(function() { i++; innerCallback(); }, 10000);
};
);
The snippet above delays the execution between loop elements for 10 seconds. But how could I delay the loop execution at a specific time for a number of seconds?
Any suggestions are much appreciated!
var delayInterval = 10000;
setTimeout(function(){
delayInterval = 30000;
}, 1000*60*30);
var i = 0;
async.whilst(
// test to perform next iteration
function() { return i <= Myobject.length-1; },
function(innerCallback){
//Some calculations....
setTimeout(function() { i++; innerCallback(); }, delayInterval );
};
);
I am new to OOP in Javascript or jQuery, I am trying to clear the interval and stop any methods inside the interval, it seems not working with what I did below.
function Timer() {
var sec = $('.timer #second');
this.runTimer = function(_currentime) {
var currentTimeing = parseInt($(_currentime).text());
this.timeInterval = setInterval(function() {
$('.projects li span.second').text(currentTimeing++)
}, 1000);
$("#stop").click(function() {
// clear interval
clearInterval(this.timeInterval);
})
}
}
var play = new Timer();
$("#start").click(function(){
//console.log(this.runTimer())
play.runTimer('#second');
})
You are using this in context of different functions, that's why it's not working fine. Try:
function Timer() {
var sec = $('.timer #second');
this.runTimer = function(_currentime) {
var currentTimeing = parseInt($(_currentime).text()), that = this;
that.timeInterval = setInterval(function(){
$('.projects li span.second').text(currentTimeing ++)
}, 1000);
$("#stop").click(function(){
// clear interval
clearInterval(that.timeInterval);
})
}
}
var play = new Timer();
$("#start").click(function(){
//console.log(this.runTimer())
play.runTimer('#second');
})
I'm simply saving reference to correct this in that variable, so I can later use it to clear interval.
function Timer() {
var sec = $('.timer #second');
var timeinterval; // declare timeinterval variable here
this.runTimer = function(_currentime) {
var currentTimeing = parseInt($(_currentime).text());
timeInterval = setInterval(function(){
$('.projects li span.second').text(currentTimeing ++)
}, 1000);
$("#stop").click(function(){
// clear interval
clearInterval(timeInterval);
})
}
}
var play = new Timer();
$("#start").click(function(){
//console.log(this.runTimer())
play.runTimer('#second');
})