retain differents setInterval with a cookie or localstorage? - javascript

I have an automatic mouse with a time interval when I go inside a web. But I have a button that increase that speed but of course when I refresh the page or I go to other part of the web the speed is the first one. I tried with a cookie but I don't know how to do it because by default cookies or localstorage works only with names...
// Default speed
$(document).ready(function() {
t = setInterval(clickbutton, 3000);
}
// Button
function aumentar() {
clearTimeout(t);
t = setInterval(clickbutton, 100);
}
I will be really grateful for your help because I'm going crazy.
Thanks a lot!

The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.
The function is only executed once. If you need to repeat execution, use the setInterval() method.
Use the clearTimeout() method to prevent the function from running.
The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).
The setInterval() method will continue calling the function until clearInterval() is called, or the window is closed.
HTML local storage; better than cookies.
Create a localStorage name/value pair with localStorage.setItem("name", "value")
Retrieve the value of "name" and insert it into the element with localStorage.getItem("name")
remove item localStorage.removeItem("name")
var t;
function speed(_speed, boo){
if(boo){
return localStorage.getItem("speed") || 3000;
} else {
localStorage.setItem("speed", _speed);
}
}
$(document).ready(function() {
t = setInterval(clickbutton, speed(true));
// Button
function aumentar() {
clearInterval(t);
speed(100);
t = setInterval(clickbutton, 100);
}
});

Related

How to stopp every running javascript function (also inline)

Hi I'm trying to create a script which can stop every Javascript function.
e.g
<button onclick='doSomething()'></button>
or
setInterval(doSomething, 200);
Is it possible to stop and disable those functions with another Javascript-File
I mean get every interval like getElementByTanName(interval) and the a for function to clear them all
You need assing interval to variable, then you will be able to stop it using clearInterval function.
var interval = setInterval(function, 5000)
if(finished){
clearInterval(interval);
}

setInterval in javascript based on changes made

I'm having an issue with a javascript requirement. I have a html calling a script perpetually every 1500ms using setInterval.
var t = setInterval(loadData(),1500);
The loadData function calls a script which returns a JSON as a list, what I want to do is to change from a fixed interval to a variable interval. For instance, if there are no changes made between two calls to the script, I must set another value for the interval. I heard I could use jquery linq to compare the length of the list at the beginning and the list when refreshing to change the time value. I also heard I could save the value of count in a cookie to compare always.
Any idea please? I would be grateful. Thanks in advance.
I'm guessing you're trying to do:
var speed = 1500,
t = setInterval(loadData, speed);
function loadData() {
if (something == true) {
something = false;
speed = 3000;
clearInterval(t);
t = setInterval(loadData, speed);
}else{
//do something
}
}
You should just reference the function, adding the parenthesis runs the function immediately. When using a variable for the speed, you'll need to clear and run the interval function again to change the speed.
if the interval is variable, then you can't use setInterval, which period won't be changed after the first call. You can use setTimeout to alter the period:
var period=1500
var timer;
var callback = function() {
loadData();
timer = setTimeout( callback, period )
};
var changePeriod = function( newPeriod ) {
period = newPeriod;
}
//first call
callback();
now, you just need to call changePeriod( ms ) to change the period afterwards

Cant get javascript intervals to work

so im a little new to javascript, but im trying to make a progress bar, with some other functionalities, on click of a button. im tring to use the set interval in javascript in order to time the bar, this is my js so far:
//Javascript Document
function progress(){
Var uno = setTimeout("uno()", 3000);
uno(){
document.getElementById("title").innerHTML = "Connecting...";
document.getElementById("progressInner").style.display = 'block';
document.getElementById("progressInner").style.width = '20px';
}
}
From what i have gathered this is how it works, however i am skeptical as it seems i am setting a variable uno but not doing anything with it.... from my background in php, thats not how that works :p any pointers you guys can give me on this? my html is here: http://jsbin.com/apoboh/1/edit
right now, it does nothing, it gives me : Uncaught ReferenceError: progress is not defined
first, you are using setTimeout not setInterval. The former fires the callback once, the latter indefinitely at a set interval.
Second, these methods return a token that you can use to cancel a setInterval, do this instead
function startProgress(){
// only start progress if it isn't running
if (!App.progressToken) { // App is you apps namespace
App.progressToken = setInterval(function(){
document.getElementById("title").innerHTML = "Connecting...";
document.getElementById("progressInner").style.display = 'block';
document.getElementById("progressInner").style.width = '20px';
}, 3000);
}
}
later, when you want to stop:
function stopProgress(){
clearInterval(App.progressToken);`
delete App.progressToken
}
The variable uno simply holds the handle to the timeout that you just set. You can later use it to clear the timeout before it executes if you need to via a call to clearTimeout().
If you don't need to clear the timeout, then there's really no reason to store the handle at all.
function progress(){
function uno(){
document.getElementById("title").innerHTML = "Connecting...";
document.getElementById("progressInner").style.display = 'block';
document.getElementById("progressInner").style.width = '20px';
}
var timeoutFunc = setTimeout(uno, 3000);
}
You pass a function to setTimeout which it will call later, not a string. So this code will define a function uno, and then pass it to setTimeout and delay 3 seconds then call it every 3 seconds after that.
You forgot to put word "function " before uno()

Resetting setTimeout object if exists

When somebody clicks my checkboxes, from a long list of checkboxes, I want to show the number of selected checkboxes in a little popup element. My problem is, the little popup element should disappear 5 seconds after the last click, which is OK for one checkbox being clicked, but if I quickly check 5 boxes, the timer is still set on the first box, resulting in the popup element disappearing too quickly.
As you can see in my function, I've tried using the clearTimeout(timeoutName) function but have experienced some troubles applying it. The console log states that the clearTimeout(timeoutName) is undefined, which I can understand: the setTimeout hasn't even started yet.
How can I check that the timer exists before I clear it? Or is this really not the best method? When a checkbox is checked (this function runs) there could be a timer running but sometimes there could not be.
$('.name_boxes').live('click', function() {
var checked_count = $('.name_boxes:checked').length;
// other stuff
clearTimeout(hide_checked_count_timer); // if exists????????
$(".checked_count").hide();
$(".checked_count").text(checked_count+" names selected");
$(".checked_count").show();
hide_checked_count_timer = setTimeout(function() {
$(".checked_count").hide();
},5000);
});
Any help gratefully received...
Just declare the timer variable outside the click handler:
var hide_checked_count_timer;
$('.name_boxes').live('click', function() {
var checked_count = $('.name_boxes:checked').length;
// other stuff
clearTimeout(hide_checked_count_timer); // if exists????????
$(".checked_count").hide();
$(".checked_count").text(checked_count+" names selected");
$(".checked_count").show();
hide_checked_count_timer = setTimeout(function() {
$(".checked_count").hide();
},5000);
});
http://jsfiddle.net/kkhRE/
Considering .live has been deprecated, you should be delegating the event with .on instead:
// Bind to an ancestor. Here I'm using document because it an
// ancestor of everything, but a more specific ancestor
// would be preferred.
$(document).on('click', '.name_boxes', function() {
// ...
});
Q. The console log states that the clearTimeout(timeoutName) is undefined, which I can understand: the setTimeout hasn't even started yet.
A. The clearTimeout() function's return value is undefined regardless of whether there was a timeout to be cleared. It doesn't have a concept of "success" that can be tested. If there is a queued timeout associated with the id you pass then it will be cleared, otherwise nothing happens.
Q. How can I check that the timer exists before I clear it?
You can't, at least not in the sense of there being some registry of outstanding timeouts that you can query. As you already know, the .setTimeout() function returns an id for the timeout just queued, and you can use that id to clear it before it runs, but there is no way to test whether it has already been run. The id is just a number so the variable that you saved it in will continue to hold that number even after the timeout has either run or been cleared.
It does no harm at all to call clearTimeout() with an id for a timeout that already ran - basically if the timeout for that id is in the queue it will be cleared otherwise nothing will happen.
The easiest way to test "Is there an outstanding timeout that hasn't run yet" is to set the variable holding the timerid to null when the timeout runs, i.e., within the function you queued:
var timerid = setTimout(function() {
timerid = null;
// other operations here as needed
}, 5000);
// in some other code somewhere
if (timerid != null) {
// timer hasn't run yet
} else {
// timer has run
}
The variable you save the timerid in needs to be in a scope that can be accessed both where you set it and where you test it, i.e., don't declare it as a local variable within an event handler.
You can use the power of short-circuit operators
hide_checked_count_timer && clearTimeout(hide_checked_count_timer);
The right-hand statement will only run if the left-hand variable is not undefined.
to check if it exists use;
if (typeof timerid == 'undefined')
{
//timer has not been set so create it
timerid = setTimeout(function(){ var something = true;}, 5000);
}

How can I run some code on all the nodes in a tree?

I want to run some code on all my treeView nodes depending on a value returned from the database and repeat this until a certain value is returned.
I was thinking that:
Give all my tree nodes the same css class so I can access them from JQuery
have a timer in my JQuery function that used ajax to go to the database, when a certain value is returned then stop the timer
Two questions here. How can I make my function run for each of the nodes and how do I do a timer in JavaScript, so:
$(function(){
$('cssClassOfAllMyNodes').WhatFunctionToCallHere?((){
//How do I do Timer functionality in JavaScript?
ForEachTimeInterval
{
//use Ajax to go to database and retrieve a value
AjaxCallBackFunction(result)
{
if (result = 1)
//How to stop the timer here?
}
}
});
});
Hope i'm clear. Thanks a lot
thanks a lot for the answer. And i would like you to comment on the design.
Bascially what i'm trying to acheive is a Windows Wokflow type functionality where each node in my tree updates its image depending on its status, where its status is got from querying the database with a key unique to the tree node. I'm open to ideas on other ways to implement this if you have any. thanks again
Without commenting on your design you can refer to these
$.each()
setTimeout() or setInterval()
You can do:
$(function(){
$('cssClassOfAllMyNodes').each(function (){
// Do something with "this" - "this" refers to current node.
});
});
Te proper way to handle timers in JS is to have a reference to each timeout or interval and then clearing them out.
The difference between them is:
The timeout will only run once, unless stopped before;
The interval will run indefinitely, until stopped.
So you can do something like:
var delay = 2000; // miliseconds
var timer = setTimeout("functionToBeCalled", delay);
clearTimeout(timer); // whenever you need.
Please note you can pass a string to setTimeout (same with setInterval) with the name of the function to be called. Or you could pass a reference to the function itself:
var callback = function () { alert(1); };
var timer = setTimeout(callback, delay);
Be sure not to set an Interval for AJAX requests, because you response might be delayed and successive calls to the server could eventually overlap.
Instead, you should call setTimeout and when the answer arrives then call setTimeout again.

Categories

Resources