Run the function until the mouse button is pressed in JavaScript - javascript

I want the function to run continuously as long as the user presses the mouse button
But it runs only once and is printed once on the console
I do not know how to solve this problem
please guide me
function handleBye() {
return console.log("BYE");
}
function handleHello() {
return console.log("HELLO");
}
<button onmousedown="handleHello()">hello</button>
<button onmousedown="handleBye()">bye</button>

Maybe you are looking for setInterval and clearInterval:
let timer;
function stop() {
clearInterval(timer);
}
function handleHello() {
repeat(() => console.log("HELLO"));
}
function handleBye() {
repeat(() => console.log("BYE"));
}
function repeat(what) {
timer = setInterval(what, 200); // Schedule
what(); // Also do it immediately
}
<button onmousedown="handleHello()" onmouseup="stop()">hello</button>
<button onmousedown="handleBye()" onmouseup="stop()">bye</button>

Related

Remember if button was clicked + Stop interval doesnt work

so I'm trying to create two buttons. One is refreshing site on interval and second one should stop it after pressing, but the stop button isn't working. Second thing is that if I press start button it's not saved in local storage as I want it. Could you guys help me with this?
window.onload = function () {
if (localStorage.getItem("refresh")) {
startref()
}
};
function startref() {
let intervalId = setInterval(function () {
chrome.tabs.query({ active: true, currentWindow: true }, function (arrayOfTabs) {
var code = 'window.location.reload();';
chrome.tabs.executeScript(arrayOfTabs[0].id, { code: code });
});
}, 1000);
localStorage.setItem('refresh');
}
function stop() {
clearInterval(intervalId);
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("startbtn").addEventListener('click', startref);
});
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("stopbtn").addEventListener('click', stop);
});
localStorage.setItem function takes two arguments. One is key and another is the value for the key.
change this line
localStorage.setItem('refresh');
into this
localStorage.setItem('refresh',intervalId);
When you clear the interval first get the intervalId stored in the localStorage and then call clearInterval.
function stop() {
const intervalId = localStorage.getItem("refresh");
clearInterval(intervalId);
}

clearTimeout on mouseup doesnt work right

I want to click on a point and delete it, but when i press my mouse button down for 3 seconds, i want to do something else with this point. My problem is, that the code doesnt clear the timer, it just deletes the point after 3 seconds, no matter how long i clicked it on the point.
Im working with setTimeout and clearTimeout.
function click(event,d){
timer= setTimeout(function(){
/* do something */
},3000)
}
function clickRelease(timer){
clearTimeout(timer)
}
divMag1=d3.selectAll(".scatterlayer .trace .points path ")
divMag1.on("mousedown", click)
divMag1.on("mouseup",clickRelease)```
V3 - I think you're deleting the target before you can execute what you want.
Note that setTimout may take more than 3 seconds to execute.
Try:
function click(event) {
const currentTarget = event.currentTarget; // for some reason event.target is null in the timer handler, this fixes it 🤷
const timer = setTimeout(() => {
currentTarget.removeEventListener('mouseup', deleteTarget);
console.log('stuff');
// do stuff
}, 3000);
function deleteTarget() {
clearTimeout(timer);
console.log('deleted');
currentTarget.removeEventListener('mouseup', deleteTarget); // not required if you're actually deleting the target
// remove target
}
currentTarget.addEventListener('mouseup', deleteTarget);
}
document.querySelector('#but').addEventListener('mousedown', click)
<button id="but">Click</button>
V1:
let timer;
function click(event,d){
timer= setTimeout(function(){
/* do something */
},3000);
}
function clickRelease(){
clearTimeout(timer)
}
divMag1=d3.selectAll(".scatterlayer .trace .points path ")
divMag1.on("mousedown", click)
divMag1.on("mouseup",clickRelease)
You should first declare timer variable. Then to make your mouseup event works on you should wrap clickRelease to event funtion again or use it simply:
...
.addEventListener("mouseup", function() { clearTimeout(timer) })
Working example with button:
var timer
function click(event, d) {
timer = setTimeout(function () {
console.log('do something')
}, 1000)
}
function clickRelease(timer){
clearTimeout(timer)
}
var divMag1 = document.querySelector('#but')
divMag1.addEventListener("mousedown", click)
document.addEventListener("mouseup", function() { clickRelease(timer) })
<button id="but">Click</button>
If you want event to doing something repeatedly while button is down you need to use setInterval not setTimeout like this:
var timer
function click(event, d) {
timer = setInterval(function () {
console.log('do something')
}, 1000)
}
var divMag1 = document.querySelector('#but')
divMag1.addEventListener("mousedown", click)
document.addEventListener("mouseup", function() { clearInterval(timer) })
Note for clearing interval uses clearInterval not clearTimeout. Also the mouseup event handler attached on whole document in my solution not on button.

Can't see the issue on why my event handler is not firing my function

I am creating an input and I want to create a console log 5 seconds after the last key down. I am trying to handle this through a debounce function but can't see where I am messing it up. It is not firing the log.
<div>
<input id="test" onkeydown="handleDebounce(logIt, 5000)"/>
</div>
function logIt() {
console.log('testing');
}
function handleDebounce(fn, delay) {
let timeoutId;
return function() {
if (timeoutId) {
clearTimeout(timeoutId)
}
timeoutId = setTimeout(() => {
fn();
}, delay);
}
}
It is not logging anything. I tried tracing the issue but can't tell.
I was able to get it working by:
Fixing the broken console.log reference.
Moving the declaring of timeoutID outside of the function.
and removing the returning of the anonymous function that doesn't return anything and isn't actually being called.
function logIt() {
console.log('testing');
}
var timeoutId;
function handleDebounce(fn, delay) {
if (timeoutId) {
clearTimeout(timeoutId)
}
timeoutId = setTimeout(() => {
fn();
}, delay);
}
<div>
<input id="test" onkeydown="handleDebounce(logIt, 5000)"/>
</div>
Because from handleDebounce, you are returning function that will actually create the timer and so on, but that function is never executed, you should either do the logic in handleDebounce, or call the function, in html:
<input id="test" onkeydown="handleDebounce(logIt, 5000)()"/>
When attaching the inline event handlers, you will also have to invoke the function and not just the function reference.
A cleaner way to write this is to remove the inline event handler and add the handler in the JS
<input id="test" onkeydown="handleDebounce(logIt, 5000)()"/>
document.querySelector('#test').addEventListener('keydown', handleDebounce(logIt, 2000))
function logIt() {
console.log('testing');
}
function handleDebounce(fn, delay) {
let timeoutId;
return function() {
if (timeoutId) {
clearTimeout(timeoutId)
}
timeoutId = setTimeout(() => {
fn();
}, delay);
}
}
<div>
<input id="test" />
</div>

How can I reset the timer again using clearInterval()?

I have looked at the other threads about this question, but so far I have found no solution that fits my problem. I want to create a timer that activates using an addEventListener, in which I will use a setInterval(). Then I want to have a "pause" button that can pause the setInterval(), which I did by using clearInterval().
My problem is that, once I pause my timer once, I cannot get the timer to continue counting again by clicking the same button that starts the timer in the first place. This is my code:
hour=document.getElementById("hour");
minute=document.getElementById("minute");
second=document.getElementById("second");
start=document.getElementById("start")
reset=document.getElementById("reset")
pause=document.getElementById("pause");
var countdown;
start.addEventListener("click", function clicked() {
countdown = setInterval(function() {
if (second.textContent!="59") {
let new_second=Number(second.textContent)+1;
second.textContent=new_second;
}
else {
second.textContent="00";
if (minute.textContent!="59") {
let new_minute=Number(minute.textContent)+1;
minute.textContent=new_minute;
}
else {
minute.textContent="00";
let new_hour=Number(hour.textContent)+1;
hour.textContent=new_hour;
}
}
}, 1000)
this.outerHTML=this.outerHTML;
}, false);
pause.addEventListener("click", function() {
clearInterval(countdown);
})
reset.addEventListener("click",function() {
clearInterval(countdown);;
second.textContent="00";
minute.textContent="00";
hour.text.Content="00";
})
Thank you all for your help!
outerHTML destroys the original start button (and creates a new instance), and thus the event listener you attached to it is no longer valid. Fixed code here:
hour=document.getElementById("hour");
minute=document.getElementById("minute");
second=document.getElementById("second");
start=document.getElementById("start")
reset=document.getElementById("reset")
pause=document.getElementById("pause");
var countdown;
start.addEventListener("click", function clicked() {
// alternatively you can clearInterval here every time
if(!countdown)
countdown = setInterval(function() {
if (second.textContent!="59") {
let new_second=Number(second.textContent)+1;
second.textContent=new_second;
}
else {
second.textContent="00";
if (minute.textContent!="59") {
let new_minute=Number(minute.textContent)+1;
minute.textContent=new_minute;
}
else {
minute.textContent="00";
let new_hour=Number(hour.textContent)+1;
hour.textContent=new_hour;
}
}
}, 1000)
}, false);
pause.addEventListener("click", function() {
clearInterval(countdown);
countdown=null;
})
reset.addEventListener("click",function() {
clearInterval(countdown);
countdown=null;
second.textContent="00";
minute.textContent="00";
hour.textContent="00";
})
<div id="hour"></div>
<div id="minute"></div>
<div id="second"></div>
<div id="start">start</div>
<div id="reset">reset</div>
<div id="pause">pause</div>

How to make .one () method to work again without reloading the page

I have a chat application and I made that when the user writes in the TEXTAREA field to add a text under his name for example Typing ... but for personal reasons I would like this "Typing ..." to appear only once without repeating for each character.
I tried with the one () function but it works again only if user reloads the page.
$("textarea").one('input', function () {
HERE IS MY CODE TO ADD "TYPING.." UNDER HIS NAME
});
function sendMessage() {
HERE IS MY CODE TO DELETE "TYPING..." FROM UNDER HIS NAME
}
How can I make it work?
You could use a kind of throttling, using the following setTimeout-based, function:
// Returns a function that will call its callback argument
// only when a certain delay has passed. Another callback
// can be called to notify that the delay has expired
function throttle(f, milliseconds, ready = () => null) {
let timer = -1;
return function () {
if (timer === -1) f();
clearTimeout(timer);
timer = setTimeout(function () {
timer = -1;
ready();
}, milliseconds);
}
}
function sendMessage(msg) {
$("div").text("typing...");
}
function clearMessage() {
$("div").text("");
}
$("textarea").on('input', throttle(sendMessage, 3000, clearMessage));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea></textarea>
<div></div>
The "typing..." message will clear when during 3 seconds there was no typing. If typing starts again, then the message will be sent/displayed again. The message will not be sent again before it has been cleared.
You could work with a timeout, that will revert the typing state after a certain time. Clear the timeout while the user keeps typing.
const textArea = document.querySelector('.area')
const indicator = document.querySelector('.indicator')
let timeout = null
textArea.addEventListener('input', function() {
clearTimeout(timeout)
indicator.innerText = 'Typing...'
timeout = setTimeout(function() {
indicator.innerText = ''
}, 300)
})
.area,
.indicator {
display: block;
margin: 1rem;
}
<textarea class="area"></textarea>
<span class="indicator"></span>

Categories

Resources