Somehow my same closed ,because the question was not clear to everyone.
I a repeating the same question.
Here i have this input field when the user is typing I am calling handleMessagePress(e) function continuously ,and when the user stops typing I, am calling stop() function after five seconds . But my question is when the user starts typing , i need to call handleMessagePress(e) function only once and wait for 5 seconds and if the user is still typing the same function should be called automatically otherwise the stop function should be called automatically. In simpler words after 5seconds my Program should be able to check user is typing or not whether the user is typing or not if typing call handleMessagePress(e) otherwise call stop function automatically
<input placeholder="type your message" id="messageInputField" onKeyPress={(e) => handleMessagePress(e)}/>
let myInput = document.getElementById("messageInputField");
let timer;
if (myInput) {
myInput.addEventListener("keyup", () => {
clearTimeout(timer);
timer = setTimeout(stop, 5000);
});
}
const stop=()=>{
console.log("user stop typing");
}
const handleMessagePress = (e) => {
console.log("user is typing");
}
let myInput = document.getElementById("messageInputField");
let timer;
let executeHandlePress = true; // flag to watch handle press function execution
if (myInput) {
myInput.addEventListener("keyup", () => {
clearTimeout(timer);
timer = setTimeout(stop, 5000);
});
}
const stop=()=>{
console.log("user stop typing");
}
const handleMessagePress = (e) => {
if(!executeHandlePress){ // if flag false, return
return;
}
console.log("user is typing"); // if true execute
executeHandlePress = false; // toggle flag to false
setTimeout(()=>{
executeHandlePress = true; // reset after 5 seconds
}, 5000);
}
<input placeholder="type your message" id="messageInputField" onKeyPress=" handleMessagePress(event)" />
Related
I have a form that counts when a button (button.clicked in the example below) is clicked. I want to make it operate in two modes: one keeps counting with every click, the other has a timer (started with the click of another button, button.start) that will disable the click-count button when the timer runs out. Each mode is chosen by clicking a button (button.menu-timer and button.menu-clicks). When the count mode is selected, one function (cc) is called. When switched to the timer mode, another function (tt) should be called and the first function should stop.
If I click one mode button, then everything works as it should, but if after that I click the other mode button, both functions continue to operate; each click of button.click adds two to the count. Moreover, if you click the mode buttons several times, clicking the count button will increase the counter many times, rather than only once.
I searched for solutions on the Internet and found one based on return; I tried to use return in various ways but couldn't get it to work.
I need that when choosing the right mode, only the desired function works. And so that when you click several times on one mode, the function will run once.
The following snippet is also available on CodePen.
let clicker = document.querySelector(".click");
let start = document.querySelector(".start");
let clickerValue = document.querySelector(".click").value;
const reset = document.querySelector(".reset");
const menuTimer = document.querySelector(".menu-timer");
const menuClicks = document.querySelector(".menu-clicks");
const times = document.querySelectorAll(".time");
let i = 0;
let y;
let tf;
let timer = 15;
function tt(tf) {
if (tf ===2) {
return;
}
start.addEventListener("click", () => {
start.style.zIndex = "-1";
y = setInterval(() => {
if (i === timer) {
clicker.setAttribute("disabled", "");
} else {
i++;
}
}, 1000);
});
clicker.addEventListener("click", () => {
clicker.textContent = clickerValue++;
});
reset.addEventListener("click", resetF);
}
function cc(tf) {
if (tf = 1) {
return;
}
start.addEventListener("click", () => {
console.log("111111");
start.style.zIndex = "-1";
});
clicker.addEventListener("click", () => {
clicker.textContent = `a ${clickerValue++}`;
});
reset.addEventListener("click", resetF);
}
function resetF() {
clearInterval(y);
i = 0;
start.style.zIndex = "2";
clickerValue = 0;
clicker.textContent = clickerValue;
clicker.removeAttribute("disabled", "");
}
menuTimer.addEventListener("click", function () {
menuTimer.classList.add("active");
menuClicks.classList.remove("active");
tt(1);
resetF();
});
menuClicks.addEventListener("click", function () {
menuClicks.classList.add("active");
menuTimer.classList.remove("active");
cc(2)
resetF();
});
<div class="menu">
<button type="button" onclick="tf = 1" class="menu-timer">TIMER</button>
<button type="button" onclick="tf = 2" class="menu-clicks">CLICKS</button>
</div>
<div class="click-btn">
<button class="click" type="button">0</button>
<button class="start" type="button">START</button>
</div>
<button class="reset" type="button">Reset</button>
You have a typo with assigning = instead of equality operator ===
function cc(tf) {
if (tf = 1) { // should be ===
return;
}
...
}
Also before you addEventListener('click', ...), a good practice is to remove previous click listeners with removeEventListener('click')
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);
}
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>
I have this code:
input.addEventListener('keydown', (event) => {
if (event.keyCode === 13 && input.value) {
sendText(input.value);
var response = responseChat(input.value, 'user');
insertResponse(response);
input.value = '';
}
});
In this code, the client types some words to send to app web. So, I need when, the client not type and send some, the page sends a message of: "You are not work!!"
I create this function with setTimeOut but I don't know how to put this in my code:
function first(){
sendText("your are not work!");
}
function sendFirst(){
clearTimeout(time);
time = setTimeout(first, 5000);
}
Could you help me? Thanks
This is what you want. Will console.log 'you are not working!' after 3 seconds of keyboard inactivity. Click 'Run code snippet' below to try it out.
const sendText = console.log;
const input = document.getElementById('fred');
let timeout
const restart = () => {
clearTimeout(timeout);
timeout = setTimeout(() => {
sendText("you are not working!");
}, 3000);
}
restart();
input.addEventListener('keydown', (event) => {
restart();
if (event.keyCode === 13 && input.value) {
sendText(input.value);
// var response = responseChat(input.value, 'user');
// insertResponse(response);
input.value = '';
}
});
<input id="fred">
I need a function to execute when the user types something into the input box. The function should make the input box uneditable for 3 seconds, before making the input box editable again. I have the function below, but it's not working at all. I'm wondering what I did wrong, and how to fix it?
function makeUnedit (id) {
setTimeout(function(){ document.getElementById(id).readOnly = false; }, 3000);
success:function(setTimeout) {
document.getElementById(id).readOnly = true;
}
}
Edit:
This one works, but if you spam the input box, like you enter 1 input per 100 milliseconds or so, it'll override it, make the readOnly true all the time if you keep spamming it at that rate.
document.getElementById(id).readOnly = true;
setTimeout(function(){ document.getElementById(id).readOnly = false; }, 1500);
This will work:
function makeUnedit (id) {
document.getElementById(id).readOnly = true;
setTimeout(function(){
document.getElementById(id).readOnly = false;
}, 3000);
}
Note, that the function you pass as argument to setTimeout(argument, milliseconds) will get called after x milliseconds passed.
success: is a senseless parameter here and should have thrown a syntax error.
window.onload = function() {
function makeUnedit (id) {
document.getElementById(id).readonly = true;
window.setTimeout(function() {
document.getElementById(id).readonly = false;
}, 3000);
}
document.getElementById("id").onfocus = function() { makeUnedit ("id") };
};
<input type="text" id="id"/>
By my reckoning, your use of the success keyword appears to be incorrect. As there is no need for such a statement anyhow, here is a solution.
function makeUnedit (id) {
document.getElementById(id).readonly = true;
window.setTimeout(function() {
document.getElementById(id).readonly = false;
}, 3000);
}
Add the code below for your handler:
document.getElementById(id).onfocus = function() { makeUnedit(id) };