I would like to setup a counter which can be paused as well as resumed with in a button click in javascript. But what ever i have tried can able to pause it but its not resuming from where i have paused, its starting from beginning when i perform resume operation.
below is my code what i have tried so far.
const [isPlay, setisPlay] = useState(true);
const timerRef = useRef(null);
useEffect(() => {
start();
}, []);
var counter;
function start() {
console.log('start');
if (!counter) {
reset();
} else {
loop();
}
}
function pause() {
if (timerRef.current) {
clearInterval(timerRef.current);
timerRef.current = null;
}
}
function reset() {
console.log('reset');
pause();
counter = 10;
loop();
}
function loop() {
timerRef.current = setInterval(function () {
if (0 >= counter) {
pause();
return;
}
console.warn('counter', counter);
counter--;
}, 1000);
}
const stopProgress = () => {
if (isPlay) {
pause();
setisPlay(false);
} else {
start();
setisPlay(true);
}
};
Can anyone please give me a solution for this to fix that. Answers would be much appreciated.
Related
I have a timer, I want to do something when textContent of div element === 0;
JavaScript:
function createTimer() {
const display = document.createElement('div');
display.classList.add('display');
display.id = 'display';
display.textContent = '5';
return display;
};
let intervalID;
function startTimer() {
resetTimer();
intervalID = setInterval(() => {
let displayTimer = document.getElementById('display');
let displayNumber = parseInt(displayTimer.textContent);
if (displayTimer.textContent !== '0') displayTimer.textContent = displayNumber - 1;
}, 1000);
};
function resetTimer() {
clearInterval(intervalID);
};
function someFunc() {
// here is a lot of code stuff and timer is working correctly
const timer = createTimer();
};
This is what i tried:
function someFunc() {
const timer = createTimer();
timer.addEventListener('input', () => {
if (timer.textContent === '0') {
console.log(true);
};
});
};
As far as I understood correctly, by creating input event on timer, I always get timer.textContent when it changes, right? I keep track of all the changes that's happening in this div element.
Nothing happens.
Keep track of your count as a number in JavaScript. This creates clarity in what the count is and how it can be manipulated.
Inside the setInterval callback, check if the count is 0. The interval is already there and will run every second, so it makes sense to check it in that place.
The example below is a modified version of your script with the suggested implementation. Since you're returning the display element from the createTimer function I've decided to reuse it in the startTimer function. That way you don't have to select the element from the DOM, as you already have a reference to the element.
As a bonus an extra argument which can be callback function to do something whenever the timer ends.
let count = 5;
let intervalID;
function createTimer() {
const display = document.createElement('div');
display.classList.add('display');
display.id = 'display';
display.textContent = '5';
return display;
};
function resetTimer() {
clearInterval(intervalID);
};
function startTimer(timer, onFinish) {
resetTimer();
intervalID = setInterval(() => {
if (count !== 0) {
count--;
}
if (count === 0) {
resetTimer();
if (typeof onFinish === 'function') {
onFinish();
}
}
timer.textContent = count;
}, 1000);
};
function someFunc() {
const timer = createTimer();
document.body.append(timer);
startTimer(timer, () => {
console.log('Done');
});
};
someFunc();
The input event fires when the value of an <input>, <select>, or <textarea> element has been changed by user. It does not fire when setting the textContent programmatically.
You can use the MutationObserver API to observe the node change.
const timer = createTimer();
new MutationObserver(() => {
let timer = document.getElementById('display');
if (timer.textContent === '0') {
console.log(true);
};
}).observe(timer, { childList: true });
You could implement the timer with the help of async/await code. It makes the code a lot more cleaner, by having your start and end code in the same function.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
function createTimer(name) {
const element = document.createElement("div");
element.classList.add("timer");
document.body.appendChild(element);
element.textContent = name+": -";
return async function(seconds) {
for (let second = seconds; second >= 0; second--) {
element.textContent = name+": "+second;
if (second > 0) {
await wait(1000);
}
}
};
}
async function someFunc() {
const timer = createTimer("First timer");
console.log("first timer started", new Date());
await timer(10);
console.log("timer ended", new Date());
await wait(2500);
console.log("first timer started again", new Date());
await timer(5);
console.log("first timer ended again", new Date());
}
async function someOtherFunc() {
const timer = createTimer("Second timer");
console.log("second timer started", new Date());
await timer(20);
console.log("second timer ended", new Date());
}
someFunc();
someOtherFunc();
.timer {
text-align: center;
font-size: 2em;
font-family: sans-serif;
}
https://jsfiddle.net/mhLaj3qy/1/
const changeTimeset = setTimeout(()=>{
if (is_paused) return;
bgImage.style.backgroundImage = array[current]
changeBackgroundImages(data, ++current % array.length)
}, a)
function chandgeBackgroundImageOnMouse() {
samoyed.addEventListener("mouseover", ()=>{
bgImage.style.backgroundImage = house
is_paused = true
})
samoyed.addEventListener("mouseleave", ()=>{
is_paused = false
})
}
chandgeBackgroundImageOnMouse()
}
How to pause setTimeout and then continue it? It should be like when it hovered on text - picture stops auto slider, when it mouseout - auto slider is working
Here i tried to do it with it_paused = false/true. But nothing succeeded. What am i doing wrong?
In this case, you may try using setInterval instead of setTimeout.
About setInterval:
https://www.w3schools.com/jsref/met_win_setinterval.asp
In fact, setTimeout internally can't be paused, but we can work around, it by when pause clearing the old setTimeout and checking the difference in time, and setting it in a variable called remaining, then when we resume creating a new setTimeout with the remaining time.
class Timer {
constructor(callback, delay) {
this.remaining = delay
this.callback = callback
this.timerId = undefined;
this.start = undefined;
this.resume()
}
pause() {
window.clearTimeout(this.timerId);
this.timerId = null;
this.remaining -= Date.now() - this.start;
};
resume() {
if (this.timerId) {
return;
}
this.start = Date.now();
this.timerId = window.setTimeout(this.callback, this.remaining);
};
}
const pause = document.getElementById('pause');
const resume = document.getElementById('resume');
var timer = new Timer(function() {
alert("Done!");
}, 5000);
pause.addEventListener('click', () => {
timer.pause();
})
resume.addEventListener('click', () => {
timer.resume();
})
<button id="pause">Pause</button>
<button id="resume">Resume</button>
I am just starting in javascript, I would like to have a toggle button that runs a function until it's pressed again. I have some code for the toggle:
const backgroundButton = document.getElementById("backgroundButton"); //getting button from HTML
let clickToggle = 0; //defining a veriable used to store the state of the button
backgroundButton.addEventListener("click", function(){
if (clickToggle == 0) {
console.log('button was off');
//start loop
clickToggle = 1;
}
else {
console.log('button was on');
//stop loop
clickToggle = 0;
}
});
but, I don't know how to do an infinite loop, any help is greatly appreciated!
(PS: I know infinite loops crash, that's why I'm here)
You could use setInterval and clearInterval. A truly infinite loop would look like this:
while (true) doSomething();
But that is not what anyone wants, as it will block the user interface. Using setTimeout or setInterval you allow the event loop to continue to do its work.
I'll assume you want to repeat calling the function doSomething in this demo:
const backgroundButton = document.getElementById("backgroundButton");
let timer = 0;
const output = document.getElementById("output");
backgroundButton.addEventListener("click", function(){
if (timer == 0) {
console.log('button was off');
//start loop
timer = setInterval(doSomething, 50);
}
else {
console.log('button was on');
//stop loop
clearInterval(timer);
timer = 0;
}
});
function doSomething() {
output.textContent = +output.textContent + 1;
}
<button id="backgroundButton">Start/Stop</button>
<div id="output"></div>
You can do something like this. Hopefully following with resolve you're required scenario.
let isEnabled = false;
let interval;
function clickFunction() {
isEnabled = !isEnabled; // toggle enable flag
if (isEnabled) {
console.log('Set Interval', isEnabled)
interval = setInterval(function () {
console.log('Do some work.');
}, 1000);
} else {
console.log('Clear Interval', isEnabled)
clearInterval(interval);
}
}
<button onclick="clickFunction()">Click me</button>
You can also use Window.requestAnimationFrame() for the infinite loop.
const toggleButton = document.querySelector('#toggle');
let hasBegun = false;
let anim;
const tick = () => {
if (hasBegun) {
document.querySelector('#output').textContent += '+';
};
requestAnimationFrame(tick)
};
toggleButton.addEventListener("click", function() {
if (!hasBegun) {
console.log('Starting');
hasBegun = true;
anim = requestAnimationFrame(tick);
} else {
console.log('Stopping');
hasBegun = false;
cancelAnimationFrame(anim);
anim = null;
}
});
<button id="toggle">Start/Stop</button>
<pre id="output"></pre>
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();
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);