Timer in Javascript while functions - javascript

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">

Related

Calling a function based on input field value changes in JavaScript

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)" />

Getting my last clicked buton to store in local storage

I am creating an google chrome extension and I'm trying to create a start/ stop button. For some reason when I click the stop button, it will go to the start button while on the popup but when I exit off the popup, it resets back to the other button
Im trying to get my last clicked button to store in local storage so that when i click off the extension popup it will still show the button that was opposite of last clicked. For some reason when my stop button is clicked, it doesn't seem to store the variable lastclicked in local storage
Do anyone know what the issue may be or how to resolve this?
//Start and Stop buttons for logging
const btnStart = document.getElementById("click-start");
const btnStop = document.getElementById("click-stop");
//attempt to get start/stop logging buttons to work--underwork
function Logger(isLogging) {
let logger =''
if (isLogging){
btnStart.style.display= "none";
btnStop.style.display= "block";
logger = 'logging'
addRow();
} else {
btnStart.style.display= "block";
btnStop.style.display= "none";
logger = 'not logging'
}
//using storage API to save data for last btn pressed--underwork
chrome.storage.local.set({key: logger}, function() {
console.log('value is set to ' + logger);
});
}
var lastClicked = btnStart;
//button to start/stop logging
document.addEventListener("DOMContentLoaded", function () {
//get lastClicked first to make decisons
chrome.storage.local.get({'lastClicked': lastClicked}, function(result) {
if (result = btnStart) {
//works
btnStart.style.display= "none";
btnStop.style.display= "block";
console.log("last clicked is start button");
addRow();
} else if (result = btnStop) {
//not working
btnStart.style.display= "block";
btnStop.style.display= "none";
console.log("last clicked is stop button");
} else {
console.log("else statement");
}
//works
btnStart.addEventListener("click", function() {
Logger(true);
chrome.storage.local.set({'lastClicked': lastClicked}, function() {
lastClicked = btnStart; //doesnt know if it saves
console.log('logging started successful');
});
});
//works
btnStop.addEventListener("click", function() {
Logger(false);
chrome.storage.local.set({'lastClicked': lastClicked}, function() {
lastClicked = btnStop; // doesnt know if it saves
console.log('logging stopped successful');
});
});
});
chrome.storage.local.get(['key'], function(result) {
console.log('value currently is ' + result.key);
});
First, try to fix if (result = btnStart), you assign btnStart to result and it's always true if btnStart exists.
Change with if (result === btnStart) or if (result == btnStart)
Same thing for (result = btnStop)
Edition
I've spent some time to understand what you try to achieve and by reading the storage doc for extensions.
I think this code is really more readable
document.addEventListener("DOMContentLoaded", function () {
//Don't care about which button is used, keep the logica idea... is it started?
let started = true;
//Wait for content loaded before getting element is a better idea.
const btnStart = document.getElementById("click-start");
const btnStop = document.getElementById("click-stop");
//Keep all the logic together
const setStarted = s => {
started = s;
//This is a asynchronous call, I putted everything on the callback but as you want
chrome.storage.local.set({started: started}, () => {
console.debug("Storing `started` to storage with value:", isStarted);
btnStart.style.display = started? "none" : "block";
btnStop.style.display = !started? "block" : "none";
if ( started ) {
//What's that?
addRow();
}
});
};
//Get seems to by used with a string key, not an object
chrome.storage.local.get(['started'], (result) => {
console.debug("Reading `started` from storage gives", result.started);
//Using setStarted avoid repeting always the same thing
setStarted(result.started);
});
btnStart.addEventListener("click", () => setStarted(true) );
btnStop.addEventListener("click", () => setStarted(false) );
});

Window.onload is not working inside if else statement

What's with wrong in my code?
If user input-bday match the json-bday then it will display my form(I didn't include it because it's a lot)
else it won't display the form
checkBirthday: function() {
let userBirthday = moment(this.userBday).format("MM DD, YYYY"),
resultBirtday = moment(this.results.BIRT_D).format("MM DD, YYYY");
if (userBirthday === resultBirtday) {
alert("CORRECT");
window.onload = function() {
const btn = document.querySelector("#show-form");
const form = document.querySelector(".form");
const close = document.querySelector(".close-container");
btn.addEventListener("click", () => {
form.classList.add("form-show");
close.classList.add("x-show");
});
close.addEventListener("click", function() {
close.classList.remove("x-show");
form.classList.remove("form-show");
});
};
} else {
alert("WRONG");
window.stop();
}
}
window.onload = function() {} is just assigning this method to onload event of window and the code inside it will never run because onload has already been called.
You actually don't need to write onload here. so your code would be something like this.
checkBirthday: function() {
let userBirthday = moment(this.userBday).format("MM DD, YYYY"),
resultBirtday = moment(this.results.BIRT_D).format("MM DD, YYYY");
if (userBirthday === resultBirtday) {
alert("CORRECT");
const btn = document.querySelector("#show-form");
const form = document.querySelector(".form");
const close = document.querySelector(".close-container");
btn.addEventListener("click", () => {
form.classList.add("form-show");
close.classList.add("x-show");
});
close.addEventListener("click", function() {
close.classList.remove("x-show");
form.classList.remove("form-show");
});
} else {
alert("WRONG");
window.stop();
}
}

setTimeout logic is not invoked

Could you please help me to understand why this setTimeout logic is not working
The task is simple, when a user clicks a button a function will be executed copying the text of an input and then will print a message explaining that the copy was successful, followed that should wait a second and hide the message. This last part does not work.
I share a stack snippet
(function() {
const copyText = document.querySelector('#email');
const copyButton = document.querySelector('#copy');
const messageBox = document.querySelector('#message');
function copy() {
copyText.select();
document.execCommand('Copy');
displayMessage();
}
function displayMessage() {
messageBox.innerHTML = 'Email copied';
clearMessage();
}
function clearMessage() {
const timeoutID = window.setTimeout(() => {
messageBox.innerHTML = '';
}, 1000);
window.clearTimeout(timeoutID);
}
copyButton.addEventListener('click', copy);
})();
<input type="text" id="email" value="some.user#domain.com">
<button id="copy">Copy</button>
<span id="message"></span>
Thanks for your time
You're immediately clearing the timeout after you set it with window.clearTimeout(timeoutID);. Just remove window.clearTimeout(timeoutID); and it will work.
There's no need to use clearTimeout unless you want to cancel the timeout and keep its callback from being called.
Clear you timeout inside the function as-
function clearMessage() {
const timeoutID = window.setTimeout(() => {
messageBox.innerHTML = '';
window.clearTimeout(timeoutID); // place it here
}, 1000);
}
So, after one second, your unnecessary timeout will be cleared.
You clear the timer straight after declaring it. Remove the window.clearTimeout() call and it will work
Use window.clearTimeout(timeoutID); at the end of your timeout function because setTimeout is async
(function() {
const copyText = document.querySelector('#email');
const copyButton = document.querySelector('#copy');
const messageBox = document.querySelector('#message');
function copy() {
copyText.select();
document.execCommand('Copy');
displayMessage();
}
function displayMessage() {
messageBox.innerHTML = 'Email copied';
clearMessage();
}
function clearMessage() {
const timeoutID = window.setTimeout(() => {
messageBox.innerHTML = '';
window.clearTimeout(timeoutID);
}, 1000);
}
copyButton.addEventListener('click', copy);
})();
<input type="text" id="email" value="some.user#domain.com">
<button id="copy">Copy</button>
<span id="message"></span>

event for file upload cancel in javascript

We can use file.onchange if we gonna set an event callback for file reading using javascript, but how to set event for when user cancel the upload (close the browse panel)?
There is no API for the file input modal. Besides, if the user closes the browser your code won't be running anymore, will it?
Of course there is the window.onunload method which allows you to detect the example you give.
Per the comments, the best thing I can come up with that would be helpful is that if nothing is selected, file.value.length will be 0.
That’s a great solution:
const createUpload = () => {
let lock = false
return new Promise((resolve, reject) => {
const el = document.createElement('input');
el.id = +new Date();
el.style.display = 'none';
el.setAttribute('type', 'file');
document.body.appendChild(el)
el.addEventListener('change', () => {
lock = true;
const file = el.files[0];
resolve(file)
document.body.removeChild(document.getElementById(el.id));
}, { once: true })
window.addEventListener('focus', () => { // file blur
setTimeout(() => {
if (!lock && document.getElementById(el.id)) {
reject(new Error('onblur'))
document.body.removeChild(document.getElementById(el.id))
}
}, 300)
}, { once: true })
el.click() // open file select box
})
}
Ussage:
// $label.classList.add('loading');
createUpload()
.then(function (file) {
// Sent file
// $label.classList.remove('loading');
})
.catch(function (err) {
// Your Cancel Event
// $label.classList.remove('loading');
});
It is very simple with jQuery :
$("#fileInputId").change(function () {
//implement your code here
});

Categories

Resources