I've been stuck at watching a boolean variable. On my program I am setting the value of mutexSelect "true". Whenever the value is true, makeIntoSelect function must be called like below;
(here I want to declare to watch muteSelect value continuously){
if (mutexSelect == true) {
mutexSelect = false;
makeIntoSelect(newSelectedItem);
}
});
How can I check the value of mutexSelect continuously?
Thanks!
Well this solution is like using duct tape to fix something that really needs a replacement piece. The best solution would be to trigger a message when the variable is updated. Not seeing how the varaible gets updated, I can not give you a good solution here. But MDN Docs can show you how to trigger a custom event.
So what is your only other choice? Using an interval and checking to see if it has been flipped.
window.setInterval( function(){
if (mutexSelect == true) {
mutexSelect = false;
makeIntoSelect(newSelectedItem);
}
},10)
You can use jQuery setInterval function. This function will trigger continuously at given interval so that you can place your code inside that function.
jQuery SetInterval
setInterval(function(){
if (mutexSelect == true) {
mutexSelect = false;
makeIntoSelect(newSelectedItem);
}
}, 1000);
Update the call back time as you wish to get this function to trigger more frequently. (i.e) Change the value from 1000 to your desired value.
Related
I have the following code that checks if there is a gyroscope available for the user to interact with. I do this in the following way:
function check_user_hardware(){
window.addEventListener("devicemotion", function(event){
if(event.rotationRate.alpha || event.rotationRate.beta || event.rotationRate.gamma){
if (!gyroscope) {
gyroscope = true;
current_interaction_mode = 'gyroscope_option';
set_user_ui_elements();
}
}else{
followMouse = true;
current_interaction_mode = 'followMouse_option';
console.log("checked for motion");
set_user_ui_elements();
window.addEventListener('mousemove', get_user_mouse_pos);
}
calculate_rotation_mesh_pos(event.rotationRate.beta, event.rotationRate.gamma);
}, function(){
console.log("generate_scene???");
generate_scene();
});
}
the problem i am having is that after this check some scene is generated.
But this scene requires a var to be set first first in the check. But the check takes to long so i added a callback after the check is completed.
But this callback never fires... Why? In other words generate_scene??? is never logged and generate_scene(); is never run.
Why is this happening? and what would be the proper way to do this?
if anything is unclear please let me know so i can clarify :)
Your problem is next: the third parameter in your .addEventListener method is function, it shouldn't be, because in documentation third parameter is Boolean if exactly "useCapture".
Try to declare generate_scene function out of check_user_hardware() and then just call it after
calculate_rotation_mesh_pos(event.rotationRate.beta,event.rotationRate.gamma);
generate_scene();
It might work.
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);
}
});
I am trying to set up a simple boolean variable in js in order to control a few things however I am having some issues relating to when it is being fired. The boolean variable is changed whenever the user clicks a button which runs the function changeVariable(). The issue is that the alerts are firing on page load and not when the user clicks a button which runs the specified function. If anyone could take a look, that would be much appreciated.
Code is here:
var triggered = false;
function changeVariable() {
triggered = ! triggered;
}
if (triggered = true) {
alert(triggered);
}
if(triggered = false) {
alert(triggered);
}
triggered = true it is an assignment. Use == or ===.
=== it checks for type also.
The issue is that the alerts are firing on page load and not when the user clicks a button which runs the specified function.
That's because the code which performs the test and does the alert is not inside the function. Move it.
Aside: = is an assignment, to perform a comparison use == or ===. For boolean tests, consider a simple if (value) instead. Also consider the use of else instead of duplicating a test with a negative modifier.
I have a probably really simple question but did not find anything about this or maybe did not find the right words for my problem.
If have a function to be executed on keypress which also changes my variable A - fine, and it works.
But now I want to give an alternative value to my variable A if the keypress event is not happening.
So I'm looking for the correct command for the naive logic of
if ("keypress event happens") {
A = 1
} else {
A = 2
}
Is there any way to do that in js or jquery with simple true/false checks for the key event?
I've been trying and trying and it did not work once.
Usually, the way one solves this problem is with a setTimeout(). You set the timer for N seconds. If the keypress happens, you cancel the timer. If the keypress doesn't happen, the timer will fire giving you your alternate event.
You probably wrap this in some sort of function that you can trigger whenever you want, but you didn't share the overall context so this is just the general idea:
$("#myObj").keypress(function(e) {
if (timer) {
clearTimeout(timer);
}
// process key
});
var timer = setTimeout(function() {
timer = null;
// key didn't happen within the alltoted time so fire the alternate behavior
}, 5000);
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);
}