this is my code, which works but i don't know how to clear timeout and clearinterval
setTimeout(function(){
setInterval( function(){
if (Math.random()> 0.1){
countdown.extendTimer(-3)
console.log("im dying")
}
}, 1000)
}, 10000)
this is what i have tried, but the diseaseInterval() just starts immediately without waiting for 5 sec
function diseaseInterval(){
if (Math.random()> 0.1){
countdown.extendTimer(-3)
console.log("im dying")
}
}
function diseaseTimeout(){
setInterval( diseaseInterval(),1000)
}
var onDisease = setTimeout(diseaseInterval(),5000)
This time i tried clearInterval inside clearTimeout itself, but it still doesn't work
var onDisease = setTimeout(function(){
disease = true;
var diseaseInterval = setInterval( function(){
if (Math.random()> 0.1){
countdown.extendTimer(-3)
console.log("im dying")}
else if (disease=false) {
clearInterval(diseaseInterval);
}
}, 1000)
}, 10000)
function cure(){
clearTimeout(onDisease);
disease = false
}
Related
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 custom animating effect task in jQuery queue. And there is a setInterval call inside it.
After some time the stop() function is being invoked. It removes the callback of currently executing task from the queue and starts executing the next one.
But setInterval from the previous effect (which already having been removed) is still running. Where should I place the clearInterval to be invoked after cancelling the task with calling the stop()?
Here is an example:
$('body')
.queue(function(next) {
var i = 0, el = this;
var interval = setInterval(function() {
el.style.backgroundColor = i++ % 2 == 0 ? '#500' : '#050';
if (i > 5) {
clearInterval(interval);
next();
}
}, 1000);
})
.queue(function() {
this.style.backgroundColor = '#005';
});
setTimeout(function() {
$('body').stop();
}, 1500);
https://jsfiddle.net/coderlex/tLd9xtjj/
Move your interval variable instantiation outside of the queue closure function, then you can clear it whenever you call stop().
var interval = null;
$('body')
.queue(function(next) {
var i = 0, el = this;
interval = setInterval(function() {
el.style.backgroundColor = i++ % 2 == 0 ? '#500' : '#050';
if (i > 5) {
clearInterval(interval);
interval = null;
next();
}
}, 1000);
})
.queue(function() {
this.style.backgroundColor = '#005';
});
setTimeout(function() {
$('body').stop();
if (interval != null) {
clearInterval(interval);
interval = null;
}
}, 1500);
Not sure about official support of this method, but after reading the jQuery sources it seems I've found the solution. There is an undocumented second argument given to the callback function of the queue task. That's the object of the current effect's hooks. The property we need named stop accordingly. If set, the closure is called only in case of manual effect stopping by stop() or finish() methods. It's not being called on clearing or setting new queue.
Here is an example:
$('body')
.queue(function(next, hooks) {
var i = 0, el = this;
var interval = setInterval(function() {
el.style.backgroundColor = i++ % 2 == 0 ? '#500' : '#050';
if (i > 5) {
clearInterval(interval);
next();
}
}, 1000);
hooks.stop = function() {
clearInterval(interval);
}
})
.queue(function(next) {
this.style.backgroundColor = '#005';
next();
});
setTimeout(function() {
$('body').stop();
}, 1500);
I got this code from: Jquery: mousedown effect (while left click is held down)
It is behaving that if I am holding the button in every 50ms it will do something.
var timeout = 0;
$('#button_add').mousedown(function () {
timeout = setInterval(function () {
value_of_something ++;
}, 50);
return false;
});
});
But what I want is to execute this part after holding down the button by 1 second and it will continuously do the action 50ms.
As I said you need to use setTimeout()
var timeout = 0;
$('#button_add').mousedown(function () {
setTimeout(function(){
timeout = setInterval(function () {
value_of_something ++;
}, 50);
} , 1000);
return false;
});
Jsfiddle
Please use this code... You have to clearTimeout when user mouseup :
var timeout = 0;
$('#button_add').mousedown(function() {
oneSecondTimer = setTimeout(function() {
timeout = setInterval(function() {
value_of_something++;
}, 50);
}, 1000);
return false;
});
$("#button_add").mouseup(function() {
clearTimeout(oneSecondTimer);
});
This code should run for 10 seconds before ending, however if you are running the function again before the 10 seconds are finished, it should clear theTimeout and start the 10 seconds over again
function start() {
let counter = 0;
let timeUp = true;
let hello;
setInterval(()=> {
counter++
console.log(counter)
},1000);
if (timeUp == false) {
clearTimeout(hello)
timeUp = true
console.log('should run again with new clock')
start()
} else {
console.log('new clock started')
timeUp = false;
hello = setTimeout(() => {
timeUp = true
console.log('end clock')
}, 10000);
};
};
When you call start() again, this new function has no reference to hello or timeUp
Try it like this:
let hello
let timeUp = true
function start() {
let counter = 0;
//let timeUp = true;
//let hello;
setInterval(()=> {
counter++
console.log(counter)
},1000);
if (timeUp == false) {
clearTimeout(hello)
timeUp = true
console.log('should run again with new clock')
start()
} else {
console.log('new clock started')
timeUp = false;
hello = setTimeout(() => {
timeUp = true
console.log('end clock')
}, 10000);
};
};
window.start = start
Inside your function start, timeUp is always set to true, and thus clearTimeout will never be called. The way you're doing things, you should make timeUp a global variable so the function has "memory" of if the time has been reached or not.
But why do you need to set two intervals? You're already keeping track of the number of seconds that have passed, so we can make use of that interval to determine when 10 seconds have passed. This simplifies things quite a bit, and allows us to get rid of the timeUp variable as well:
let interval;
function start() {
let counter = 0;
clearInterval(interval); // clear the previous interval
interval = setInterval(() => { // set a new interval
counter++;
if (counter == 10) {
console.log('end of clock');
clearInterval(interval);
}
console.log(counter);
}, 1000);
}
This achieves exactly what you want. Whenever start is called, it cancels the previous interval and creates a new one. Once 10 seconds have passed, it clears the interval.
Your approach is kind of misleading. I think a better approach would be to have a Timer Object that you can start:
function Timer() {
var self = {
// Declare a function to start it for a certain duration
start: function(duration){
self.counter = 0;
self.duration = duration;
clearTimeout(self.timeout); // Reset previous timeout if there is one
console.log("New counter starting.");
self.count();
},
// A function to count 1 by 1
count: function(){
console.log(self.counter);
self.counter++;
if(self.counter > self.duration){
console.log('Time is up.');
} else {
self.timeout = setTimeout(self.count, 1000); // not over yet
}
}
// and other functions like stop, pause, etc if needed
};
return self;
}
// Declare your Timer
var myTimer = new Timer();
// Start it on click
document.getElementById('start-btn').addEventListener('click', function(){
myTimer.start(10);
}, true);
<button id="start-btn">Start the timer</button>
Code looks like that:
function startTimer(counter) {
var interval = setInterval(function () {
counter--;
$('#timer').html(counter);
// Display 'counter' wherever you want to display it.
if (counter == 0) {
clearInterval(interval);
$('#question').html("Time ended");
setTimeout(function () {
window.location.href = "/";
}, 5000);
return false;
}
}, 1000);
}
What I want to do is, when I call this function multiple times, every time to reset timer to 30 seconds and kill all past instances. Currently it messes up with past intances when I call multiple times. What am I doing wrong?
You have to define the var interval outside the function:
var interval;
function startTimer(counter) {
interval = setInterval(function () {
counter--;
$('#timer').html(counter);
// Display 'counter' wherever you want to display it.
if (counter == 0) {
clearInterval(interval);
$('#question').html("Time ended");
setTimeout(function () {
window.location.href = "/";
}, 5000);
return false;
}
}, 1000);
}