Stopping , the timer function in an Object - javascript

Clearing the setInterval from console I tried using
clearInterval(obj.timer())
this seems not be doing the trick any idea peeps
var obj = {
timer: function timer() {
setInterval( () => { console.log('welcome') },1000)
}
}
obj.timer()
// how do I clearInteval from the console

you need to store id returned by the setInterval function.
var obj = {
id: null,
timer: function timer() {
this.id = setInterval(() => {
console.log('welcome');
}, 1000)
},
stop: function stop() {
clearInterval(this.id);
}
}
obj.timer();
you can stop the timer by calling stop function obj.stop()

Did you try this, add "return" into function
var obj = {
timer: function timer() {
return setInterval( () => { console.log('welcome') },1000)
}
};
var timer = obj.timer();
//clear timer
clearInterval(timer);

Related

How to use setTimeout without using setTimeout function

Is there a way to use setTimeout without using setTimeout inbuilt function?
I don't want to use setInterval or clearInterval either or window.use. I have gone through multiple blogs, but all those use window, setInterval or clearInterval.
For example, the below code works, but I dont want to have window.
const setTimeouts = [];
function customSetTimeout(cb, interval) {
const now = window.performance.now();
const index = setTimeouts.length;
setTimeouts[index] = () => {
cb();
};
setTimeouts[index].active = true;
const handleMessage = (evt) => {
if (evt.data === index) {
if (window.performance.now() - now >= interval) {
window.removeEventListener('message', handleMessage);
if (setTimeouts[index].active) {
setTimeouts[index]();
}
} else {
window.postMessage(index, '*');
}
}
};
window.addEventListener('message', handleMessage);
window.postMessage(index, '*');
return index;
}
const setIntervals = [];
function customSetInterval(cb, interval) {
const intervalId = setIntervals.length;
setIntervals[intervalId] = function () {
if (setIntervals[intervalId].active) {
cb();
customSetTimeout(setIntervals[intervalId], interval);
}
};
setIntervals[intervalId].active = true;
customSetTimeout(setIntervals[intervalId], interval);
return intervalId;
}
function customClearInterval(intervalId) {
if (setIntervals[intervalId]) {
setIntervals[intervalId].active = false;
}
}
console.log("1");
customSetTimeout(function() {
console.log('3s');
}, 3000);
console.log("2");
=======================================
Alternate solution:
But here, again i dont want to use clearInterval and setInterval
var setMyTimeOut = function(foo,timeOut){
console.log('inside time out');
var timer;
var currentTime = new Date().getTime();
var blah=()=>{
if (new Date().getTime() >= currentTime + timeOut) {
console.log('clear interval if');
clearInterval(timer);
foo()
}
console.log('clear interval else');
}
timer= setInterval(blah, 100);
}
console.log("1");
setMyTimeOut(function() {
console.log('3s');
}, 3000);
console.log("2");
Is there way to achieve the same but without the use setInterval and clearInterval?
I use here the requestAnimationFrame with performance.now().
Its not super exact (well setTimeout neither), but it do the work.
function sleep(delay, cb) {
function check(time, delay) {
if(time >= delay) {
cb("done");
return;
}
time = performance.now();
requestAnimationFrame(check.bind(null, time,delay))
}
check(performance.now(), delay + performance.now());
}
sleep(4000, ()=> {
console.log("sleep done");
})
console.log("i do not block the main thread");
You can use a while loop which checks a set time against the current time:
const startTime = new Date().getTime() + 3000;
let currentTime = new Date().getTime();
function customTimeout() {
while (startTime > currentTime) {
currentTime = new Date().getTime();
}
return console.log('3 Seconds')
};
customTimeout();

Clear interval inside object method

This code is part of a game where the user has a certain amount of time to input an answer.
I want to be able to clear the interval from outside of the object if the user decides to submit an answer before the allotted time has elapsed.
I have tried returning the interval with an ID so that I can call it later and whilst this does allow me to clear it from outside the outside the object, it means that the code inside the interval function is never run.
const clock = {
timer: 30,
countdown() {
let interval = setInterval(function () {
selectors.timerDisplay.textContent = clock.timer
clock.timer--
if (clock.timer < 0) {
clearInterval(interval)
selectors.wordSubmit.click();
}
}, 1000)
},
}
I appreciate I may have simply set myself up badly to clear this interval, therefore any suggestions on how I could improve it would be appreciated.
Thanks in advance.
You can use Arrow functions to leverage the context of this from your object clock
Add a method i.e clear.
Use this context to reference your inner attributes.
const clock = {
timer: 3,
interval: 0,
reset() {
this.timer = 3;
this.interval = 0;
},
clear() {
clearInterval(this.interval);
this.reset();
},
countdown() {
this.interval = setInterval(() => {
//selectors.timerDisplay.textContent = clock.timer
this.timer--;
console.log(this.timer)
if (this.timer < 0) {
clearInterval(this.interval)
//selectors.wordSubmit.click();
}
}, 1000);
},
}
clock.countdown();
setTimeout(function() {
clock.clear();
}, 1500)
See? the interval function ends after 1.5secs
You can expose a method to clear the interval
const selectors = document.querySelector('div');
const clearTimer = document.querySelector('button');
const clock = {
timer: 5,
// Initiate the interval
int: null,
// This exposes a way to clear the interval outside of the object
clearTimer() {
clearInterval(this.int);
},
countdown() {
// This is where you define this.int
this.int = setInterval(() => {
//selectors.timerDisplay.textContent = clock.timer
selectors.innerText = clock.timer.toString();
clock.timer--
console.log(clock.timer);
if (clock.timer < 0) {
this.clearTimer();
//selectors.wordSubmit.click();
}
}, 1000)
},
}
clock.countdown();
clearTimer.addEventListener('click', () => {
clock.clearTimer();
})
<div>clock.timer</div>
<button>clear timer</button>
As has been suggested in the comments, simply return the interval so it can be stopped later. For example
countdown() {
let interval = setInterval(function () {
selectors.timerDisplay.textContent = clock.timer
clock.timer--
if (clock.timer < 0) {
clearInterval(interval)
selectors.wordSubmit.click();
}
}, 1000)
return interval // added this line
},
Then, consumers can cancel the interval when they want
const interval = clock.countdown()
// and later...
clearInterval(interval)

How to Use clearInterval() Within Revealing Module Pattern

I'm writing a timer function that uses setInterval within a revealing module pattern. I can get the timer to start fine, but I'm having trouble stopping the interval.
var timer = (function() {
var startTimer = function() {
setInterval(function() {
// Do Stuff
}, 1000);
};
var stopTimer = function() {
clearInterval(timer.startTimer());
};
return {
startTimer: startTimer,
stopTimer: stopTimer
};
})();
timer.startTimer(); // Works!
timer.stopTimer(); // Doesn't Work!
Any ideas?
var timer = (function() {
var timerRef = null;
var startTimer = function() {
timerRef = setInterval(function() {
// Do Stuff
}, 1000);
};
var stopTimer = function() {
clearInterval(timerRef);
};
return {
startTimer: startTimer,
stopTimer: stopTimer
};
})();
Try this:
var timer = (function() {
var intervalId;
var startTimer = function() {
intervalId = setInterval(function() {
// Do Stuff
}, 1000);
};
var stopTimer = function() {
clearInterval(intervalId);
};
return {
startTimer: startTimer,
stopTimer: stopTimer
};
})();

How to clear interval in randomly generated function

I have several functions defined. The setInterval is picking one at random every second. How do I temporarily clear the interval to pause this behavior?
Demo:
http://jsfiddle.net/kthornbloom/NtVBZ/1/
Code:
function playZoomout() {
$('.debug').append('1');
}
function playZoomin() {
$('.debug').append('2');
}
function playPanright() {
$('.debug').append('3');
}
function playPanleft() {
$('.debug').append('4');
}
var fns = [playZoomout, playZoomin, playPanright, playPanleft]
setInterval(function () {
fns[Math.floor(Math.random() * fns.length)]();
}, 1000);
// This isn't working. Probably because the interval above isn't really named?
$('.pause').hover(function(ev){
clearInterval(fns);
}, function(ev){
timer = setInterval( fns, 1000);
});
var fns = [playZoomout, playZoomin, playPanright, playPanleft];
var fn = function () {
fns[Math.floor(Math.random() * fns.length)]();
}
var myInterval = setInterval(fn, 1000);
$('.pause').hover(function(ev){
clearInterval(myInterval);
}, function(ev){
//timer = setInterval( fns, 1000); -> this does not make sense
myInterval = setInterval(fn, 1000); // this does
});
Working demo

clearInterval(); then call interval again

I have a setInterval function
var auto_refresh = setInterval(function () {
if ($('#addNewJuicebox:visible')) {
clearInterval();
}
//rest of function
}, 8000); // refresh every 5000 milliseconds
I want to call the setInterval later again, what's the best way to do that?
Try breaking your code up into the storage of the interval and the setting.
var auto_refresh = "";
function startRefresh() {
if (auto_refresh != "") {
// already set
return;
}
auto_refresh = setInterval(function() {
if ($('#addNewJuicebox:visible')) {
clearInterval(auto_refresh);
auto_refresh = "";
}
}, 8000);
}
Added a jsfiddle example for demonstrating starting and stopping an interval
http://jsfiddle.net/Jf8PT/
This may be what you're looking for
Function TaskRunner(run, interval) {
this._taskId = null;
this._run = run;
this._interval = interval
}
TaskRunner.prototype.start = function(){
if (this._taskId) {
return; // Already running
}
this._taskId = setInterval(this._taskId, this._interval);
}
TaskRunner.prototype.stop = function(){
if (!this._taskId) {
return; // Not running
}
clearInterval(this._taskId);
this._taskId = null;
}
var task = new TaskRunner(
function(){
if ($('#addNewJuicebox:visible')) {
task.stop();
}
// Do the update
}, 5000);
Now you can call `task.start()` from anywhere in your code to restart it.
clearInterval takes in a reference to the timer that you want to clear, you need to pass that in to it:
var auto_refresh = null;
var refresh = function () {
if ($('#addNewJuicebox').is(':visible')) {
clearInterval(auto_refresh);
auto_refresh = null;
}
};
var start_refreshing = function() {
if(auto_refresh != null) return;
auto_refresh = setInterval(refresh, 8000);
};
start_refreshing();
Maybe you just want to use setTimeout() instead, so that you have the control you're looking for?

Categories

Resources