clearInterval outside of method containing setInterval - javascript

I have a messaging function that can be called several times on the same page. Each time it's called, a new message appears at the top of the screen and has a unique ID set by an incrementing global.
The general idea of the function is below:
var messageTimer = function(msgid, duration) {
...
var interval = setInterval(
function() {
...
},
duration
)
};
In the code above, a new message is created and a timer applied. If the timer runs out, the message disappears. However, if the message is clicked on anywhere except the close button, the timer should stop and the message should stay until manually closed.
How do I find the interval ID of the message box clicked? There could be 3 other boxes simultaneously open.
$('body').on('click', '.msg', function() {
});
Since I only have a class to trigger the click by I'm thinking the only possible way to find this is to set an additional field to the ID of the message box? However this method seems unnecessary and messy.

I would set a data property on the message which stores the interval ID:
var messageTimer = function(msgid, duration) {
...
var interval = setInterval(
function() {
...
},
duration
);
$("#" + msgid).data("i", interval);
};
Then recall it onclick of your message thingies:
$('body').on('click', '.msg', function() {
clearInterval(parseInt($(this).data("i"), 10));
});

Are you using html5? You could add a custom data attribute to your node. The javascript API for this feature is described here.

Related

with or without a save button for saving textarea content

I have a lot of textareas on a page and want to save the contents automatically by typing inside
$('textarea').on('input', function(){
let id = $(this).attr('data-id');
let story = $(this).val();
$.post('a_pro.php', {fn: 'tx_change', args: [id, story]}, function(data){
console.log('saved');
});
});
On server side I have a php function tx_change to store data in a mysql table.
Everything works fine, regardless what is the speed of typing, regardles I'm on a wire on wireless connection...
I even tried typing inside one textarea and at the same time pasting a content inside another one - it works - everything is saved.
Question is - why people use a SAVE button at all?
I suppose there is a hidden risk of using this?
In a second I type 4-5 characters, so each second the javascript, php and sql code is executed five times, and plus time for establishing connection and plus time for callback function (write console)...
I simply cannot believe that there is no any problem with this.
Any advice?
Yes that true you will increase overhead on server using auto save method.
if you still want auto save, you should decrease number of request and you can do it by using debounce function.
const debounce = (func, delay) => {
let debounceTimer
return function() {
const context = this
const args = arguments
clearTimeout(debounceTimer)
debounceTimer
= setTimeout(() => func.apply(context, args), delay)
}
}
var textareaElem = document.getElementById("textarea");
textareaElem.addEventListener('keyup', debounce(function() {
alert("Hello\nNo matter how many times you" +
"click the debounce button, I get " +
"executed once every 300 ms!!")
}, 300)); // <-- you can change debounce time
<textarea id="textarea"></textarea>

Counting the inverter transition for its own function

I am writing a bot for google chrome in javascript and I have a problem, namely:
I check in intervale if the user has not disconnected. If he disconnected - skip it and open a new message. If not - I want to send specific messages in sequence. Unfortunately, but the repeating interval calls the same function over and over again, i.e. sendWelcomeMessage, when I want to stop this function after one interval and use another function.
I tried to bind a parameter to a function, but it does not work like I would like.
function message() {
var exists = document.getElementsByClassName("log-disconnected")[0].getAttribute("style");
var nextBtn = document.getElementsByClassName("o-new-talk")[0];
if (exists == "display: block;") {
console.log("Stranger disconnected");
nextBtn.click();
} else {
setTimeout(sendWelcomeMessage, 4000);
}
}
setInterval(message, 3000);

Javascript executing button click on page event

I'm new to javascript, and I'm trying to see if what I want to do is possible. I want to take a current webpage that I have open in my browser, and execute new javascript. There is a timer on this page, and when it increases to a particular time, I want it to execute a button click.
This would be the time that is changing and that I want to add into a if statement:
07:34:04
Will this changing time raise an event that would cause a javascript to run? I want something along the lines of:
if time = 7:35:00 then click button.
Thanks for your help!
I'll like to make a contribution..
I don't know much about the javascript time format, but I'll post back if I can look it up.
Any way you can use a function such as this:
var waiter;
function waitForTimer(extime, fn)
{
//Here, fn is the function to be executed..
//While extime is the time at which the function is to be executed..
waiter = setInterval(function(fn,extime){
//this function will check every one second..
if( extime == time )
{
fn();
clearInterval(waiter);
}
else
log("waiting for " + time);
}, 1000);
}
I hope this helps.

Is it possible to detect idle time even across tabs?

I have a script that sends a time-sensitive notification to users when there is a new question directed to them. However, I found that some people leave their computers open and go grab lunch, therefore missing notifications.
I'm looking to put together a script that detects if the user is idle for 5 minutes, and if so, it would show them as 'offline' and close down notifications.
I was curious if it is possible to detect inactivity even across tabs? (for example if a user switches to another tab to Facebook.com and stays active there, they would be seen as 'active' even though they are not on our webpage specifically).
Everything that happens when the user is NOT on your side is impossible to track (luckily).
So not this is not possible (think about the security).
UPDATE
Now that I think of it. It is possible, however very unlikely that you can do it. If your name would have been Google you would have come a long way, because lots of websites use Google analytics. But other than that: NO not possible for reasons mentioned.
Store their last activity in a database table when they are active. You can use mouse movement, keypresses, or some other activity to update the timestamp. Periodically poll that table with an ajax call on the page on which the user would see their online/offline status. If the last active time is > 5 minutes, show them as offline or idle.
if I am on such a thing I use either the HTML5 Visibility API or fallback to blur and focus events observing when the user left the page and then returns... leaving means unfocus the browser window or tab (but still keeping the page open)
but since you wanna react on inactivity... hmmm you could start a timeout (of course that would need a global event delegation for many events to stop it if something happens like submit, click, change, mousemove and so on)
Code is:
var inactivityTime = function () {
var t;
window.onload = resetTimer;
document.onmousemove = resetTimer;
document.onkeypress = resetTimer;
function logout() {
alert("You are now logged out.")
//location.href = 'logout.php'
}
function resetTimer() {
clearTimeout(t);
t = setTimeout(logout, 3000)
// 1000 milisec = 1 sec
}
};
I wanted to implement this functionality on my clients website. Didnt find any idleal solution for this in web.Finally I had to twig my code,think of some logic and implement this.The code goes as below--
`/*Put this code inside script tag whereever you want to execute the inactivity popup*/
var t;
//set the timeout period
var timeoutPeriod = '${inactiveIntervalMillis}';
//detect various events
callUserEvents();
`
//remove the logged Out storage after popup is closed by user
function removeLocalStorage() {
localStorage.removeItem("loggedOut");
}
//call this function whenever we detect user activity
function resetUserActivity() {
resetTimer();
}
//If the user is logged out and it clicks on other tabs,the popup will be displayed there too
function checkIfUserLoggedOut() {
if (localStorage.getItem("loggedOut")) {
loadLoginModal("/includes/gadgets/popup-content.jsp", 400, 230,
undefined);
}
}
// Call this method when any window onloads,this helps to check if multiple tabs are opened by same site
function incrementCounter() {
checkIfUserLoggedOut();
if (localStorage.getItem("counter") == "NaN") {
localStorage.setItem("counter", "0");
} else {
var counter = parseInt(localStorage.getItem("counter")) + 1;
localStorage.setItem("counter", counter);
}
resetTimer();
}
//after time interval,this method will be called
function handleIdleTimedOut() {
//get the current localStorage Object
window.sharedCounter = localStorage.getItem("counter");
//If no tabs are opened,then popup will be shown here.
if (window.localCounter == window.sharedCounter) {
loadLoginModal("/includes/gadgets/popup-content.jsp", 400, 230,undefined);
localStorage.setItem("loggedOut", "true");
}
}
function resetTimer() {
//save counterin current Window object,and after timeout period you can match it,if by chance multiple tabs were opened,the counter will be different,popup wont be shown in current window at incorrect time.
window.localCounter = localStorage.getItem("counter");
clearTimeout(t);
t = setTimeout(handleIdleTimedOut, timeoutPeriod);
}
function callUserEvents(){
window.onload=incrementCounter
window.onscroll = resetUserActivity;
window.onmousemove = resetUserActivity;
window.ondblclick = resetUserActivity;
window.oncontextmenu = resetUserActivity;
window.onclick = resetUserActivity;
window.onkeypress = resetUserActivity;
window.onpageshow = resetUserActivity;
window.onresize = resetUserActivity;
window.onfocus = incrementCounter;
window.ondrag = resetUserActivity;
window.oncopy = resetUserActivity;
window.oncut = resetUserActivity;
window.onpaste = resetUserActivity;
}
`

jQuery event only every time interval

$(document).ready(function() {
$('#domain').change(function() {
//
});
});
The code inside the change function will basically send ajax request to run a PHP script. The #domain is a text input field. So basically what I want to do is to send ajax requests as user types in some text inside the text field (for example search suggestions).
However, I would like to set a time interval in order to lessen the load of PHP server. Because if jQuery sends AJAX request every time user adds another letter to the text field it would consume lots of bandwidth.
So I would like to set let's say 2 seconds as an interval. The AJAX request will be fired every time the user types a letter but with maximum frequency of 2 seconds.
How can I do that?
$(function() {
var timer = 0;
$("#domain").change(function() {
clearTimeout(timer);
timer = setTimeout(function(){
// Do stuff here
}, 2000);
});
});
$(document).ready(function() {
var ajaxQueue;
$('#domain').change(function() {
if(!ajaxQueue) {
ajaxQueue = setTimeout(function() {
/* your stuff */
ajaxQueue = null;
}, 2000);
}
});
});
What you really want to do is check how long since the last change event so you keep track of the number of milliseconds between events rather than make a call every 2 seconds.
$(document).ready(function() {
var lastreq = 0; //0 means there were never any requests sent
$('#domain').change(function() {
var d = new Date();
var currenttime = d.getTime(); //get the time of this change event
var interval = currenttime - lastreq; //how many milliseconds since the last request
if(interval >= 2000){ //more than 2 seconds
lastreq = currenttime; //set lastreq for next change event
//perform AJAX call
}
});
});
Off the top of my head without trying this in a browser. Something like this:
$('#domain').change(function() {
if (!this.sendToServer) { // some expando property I made up
var that = this;
this.sendToServer = setTimeout(function(that) {
// use "that" as a reference to your element that fired the onchange.
// Do your AJAX call here
that.sendToServer = undefined;
}, yourTimeoutTimeInMillis)
}
else {
clearTimeout(this.sendToServer);
}
});
two variables, charBuffer, sendFlag
Use a setTimeout to have a function be called every two seconds.
This function checks if the buffer has stuff in it.
If it does, it sends/empties the stuff and clears the sent flag (to false).
and It should also clear the timeout, and set it again
else it sets the flag (to true).
Everytime the user hits a key, store it in the buffer.
if the sent flag is clear (it's false), do nothing.
else (it's true) send/empty the stuff currently in the buffer and clear the flag (to false),
and It should also clear the timeout, and set it again
This will make it so that the first time you press a key, it is sent, and a minimum of 2 seconds must pass before it can send again.
Could use some tweaking, but i use this setup to do something similar.
I am coming across this problem more and more (the more i do UI ajax stuff) so i packaged this up into a plugin available here

Categories

Resources