How do you pass a variable from inside a timer event to outside the timer event ?
MyVar = false;
setTimeout(function() { myVar = true;}, 10000);
if(MyVar == true){
console.log("Hello World");
}
how to change timerStop from false to true after 30 seconds ?
render() {
const timerStop = false;
let button;
if(timerStop == true){
button = <Form onSubmit={this.onSubmit2} ><Button loading={this.state.loading2} >Button 2</Button></Form>;
}else{
button = <Form onSubmit={this.onSubmit1} ><Button loading={this.state.loading1} >Button 1</Button></Form>;
}
return (
<Layout>
<p></p>
{button}
<p></p>
</Layout>
);
}
Since setTimeout operates asynchronously, your code won't work as your if block will always be executed before the functon you passed to setTimeout.
A solution would be to place your if block inside your timer function so it will only be executed after your timer triggers and not immidiately.
Why dont you try to implement a pub-sub model here. I think there are lot of library out there could help you.
For example this
https://github.com/mroderick/PubSubJS
myVar = false;
var MY_TOPIC = 'change_value';
PubSub.subscribe(MY_TOPIC, function (msg, data) {
if(data == true){
console.log("Hello World");
}
});
setTimeout(function() {
myVar = true;
PubSub.publish(MY_TOPIC, myVar);
}, 10000);
I solved it using this code on node/react client side ,but now i got to find a way to keep it on server side so nobody can change value to false ...
state = {
Timer:false
};
const timerStop = this.state.Timer;
setTimeout(() => {
this.setState({Timer: true});
}, 10000);
Related
When I put setInterval(autoAdmit, 1000) just below the autoAdmit() function, it works but when I place it in the if statements of another function, it does not work. Any ideas on why this is happening? I can't find anything that's wrong with it. forgot to mention: the part not working is the autoAdmit() function. When I put a console.log in the function, it still logs but what is inside the for loop is not executed for some reason.
let clickIntervalId = null;
function autoAdmit() {
for (let element of document.getElementsByTagName('span')) {
if (element.innerHTML === 'Admit') {
console.log('There is someone waiting to join this meeting, automatically admitting them...');
element.click();
}
}
}
//setInterval(autoAdmit, 1000) (if it is placed here it works)
document.addEventListener('DOMContentLoaded', function() {
var checkbox = document.querySelector('#auto-admit .mdc-switch__native-control');
function isChecked() {
if (checkbox.checked ) {
// do this
if(clickIntervalId) clearInterval(clickIntervalId);
clickIntervalId = setInterval(autoAdmit, 1000); //(if it is placed here, it doesn't work)
console.log('checked')
} else {
// do that
clearInterval(clickIntervalId);
console.log('not')
}
}
checkbox.addEventListener('change', function() {
isChecked();
});
function check() {
isChecked();
}
setTimeout(check, 2000)
}
);
I wrote the function for check if button was clicked twice and if it was to measure the time between two clicks. It has to prevent multiple clicks in short time.
Button click:
$("#Save").click(function () {
dateTime1 = new Date().getTime();
BtnId = this.id;
showSaveDialog();
});
And measuring function:
ButtonWasTriggeredTwice: function () {
var result = false;
var currentTime = new Date().getTime();
var time = currentTime - dateTime1;
if (PreviousBtn === null) {
result= false;
} else {
if (PreviousBtn === BtnId) {
if ( time < 1500) {
result = true;
}
else result = false;
}
else {
result= false;
}
}
PreviousBtn = BtnId;
BtnId = null;
return result;
}
BtnId and PreviosusBtn are global scope variables.
The strange thing is this function works great when I set breakpoints in debugger. If I switch off debugger function blocks every next click on button, no matter what time interval is between clicks
You can use this solution with unbind and timeout, like this:
HTML
<input type="button" id="Save" value="save me" />
JS:
function saveEventButton(){
$("#Save").click(function () {
alert('saved!');
$("#Save").unbind('click');
setTimeout(function(){
saveEventButton();
}, 5000); // 5sec
});
}
saveEventButton();
This is the JSFiddle
UPDATE This solution is a mix from mine and Revish Patel solution
function disableTimeout(_this){
$(_this).prop('disabled','disabled');
setTimeout(function(){
$(_this).prop('disabled','');
}, 5000); // 5sec
}
$("#Save").click(function () {
alert('saved!');
disableTimeout(this);
});
This is the JSfiddle
You can also disable button when you first click is performed.
$(document).ready(function () {
$("#Save").click(function(){
$('#Save').prop('disabled','disabled');
// Perform your button click operation
});
});
I have a simple example, I found out that onsubmit requires a return value right away. I have a function that pauses 5 seconds and wait till it completes then returns the boolean value back to simulate other javascript processing action. However, the page form submission still triggers even before my function manages to return anything values. So what should I do, would using callback in JS help in my case?
<html>
<body>
<form action="test.html" onsubmit="return testing();">
<button type="submit"> hello world </button>
</form>
</body>
<script>
function testing()
{
var newState = -1;
setTimeout(function() {
if (newState == -1) {
alert('VIDEO HAS STOPPED');
output = "newText";
console.log("AFTER 5 Sec: " + output);
return false;
}
}, 5000);
//return false;
}
</script>
</html>
One option would be to call testing() in the button click itself. You can manually call submit() within the timeout function. But be sure to return false after calling testing().
For example:
<form id="myForm" action="test.html">
<button type="submit" onclick="testing(); return false;"> hello world </button>
</form>
<script type="javascript">
function testing()
{
var newState = -1;
setTimeout(function() {
if (newState == -1) {
alert('VIDEO HAS STOPPED');
output = "newText";
console.log("AFTER 5 Sec: " + output);
document.getElementById("myForm").submit();
return false;
}
}, 5000);
//return false;
}
</script>
BTW, there appears to be no need for the newState variable.
The form can't be submitted unless the 'function finishes', which it does.
The timeout will invoke a different function that runs independently at some point in the future; simply disable the the default submit action based on a flag/state of the process.
I've separated these functions so it is more clear.
var state; // undefined, 'waiting', 'done'
function waitForVideo () {
alert('VIDEO HAS STOPPED');
console.log("AFTER 5 Sec: " + output);
// call submit again (or do whatever)
state = 'done';
document.forms[0].submit();
}
function testing()
{
if (!state)
{
state = 'waiting';
// function queued for timeout - not run immediately
setTimeout(waitForVideo, 5000);
}
if (state === 'waiting') {
// don't submit - timeout not done
return false;
}
}
Hi here is my code i need to bind the values like,
output : test test test
here is my code but working,
<script type="text/javascript">
function delayMsg2() {
var timer = null;
if (timer == null)
{
timer = setInterval(rudy(), 1000);
}
else
{
clearInterval(timer);
timer = null;
}
}
function rudy()
{
document.getElementById("output2").innerHTML = document.getElementById("output2").innerHTML + " test";
}
</script>
<div>
<button onclick="delayMsg2();" >Click me!</button>
<span id="output2"></span>
</div>
what i need to change
Reference your function rudy directly:
timer = setInterval(rudy, 1000);
No need to write a closure around, like in the other answers.
Whats wrong with your code? You execute rudy() at the moment your delay2msg is executed and you pass the return value (which is void), to the setInterval() method. Not good :)
Changed your line
timer = setInterval(rudy(), 1000);
To
timer = setInterval(function(){rudy();}, 1000);
Updated Demo
You have to fix your setInterval declaration
timer = setInterval(function(){rudy()}, 1000);
Here is a fiddle.
change your code with this one and this will solve your problem of start/stop interval also.
var timer = null;
function delayMsg2() {
if (timer == null) {
timer = setInterval(rudy, 1000);
} else {
clearInterval(timer);
timer = null;
}
}
function rudy() {
document.getElementById("output2").innerHTML = document.getElementById("output2").innerHTML + " test";
}
DEMO
I am trying to write a javascript function that when called performs function DoSomething() once,
but can be triggered to perform the function repeatedly until triggered to stop.
I am using setTimeout() function. I am not sure if this is best method from performance and memory point of view.
Also I would like to avoid global variable if possible
<!DOCTYPE html>
<html>
<script src="jquery.js"></script>
<script>
var globalCheckInventory = false;
$(document).ready(function(){
// start checking inventory
globalCheckInventory = true;
myTimerFunction();
});
// check inventory at regular intervals, until condition is met in DoSomething
function myTimerFunction(){
DoSomething();
if (globalCheckInventory == true)
{
setTimeout(myTimerFunction, 5000);
}
}
// when condition is met stop checking inventory
function DoSomething() {
alert("got here 1 ");
var condition = 1;
var state = 2 ;
if (condition == state)
{
globalCheckInventory = false;
}
}
</script>
This is probably the easier way to do what you're describing:
$(function () {
var myChecker = setInterval(function () {
if (breakCondition) {
clearInterval(myChecker);
} else {
doSomething();
}
}, 500);
});
Another way to do it would be the store the timer ID and use setInterval and clearInterval
var timer = setInterval(DoSomething);
function DoSomething() {
if (condition)
clearInterval(timer);
}
I see nothing wrong with your implementation other than the pollution of the global namespace. You can use a closure (self-executing function) to limit the scope of your variables like this:
(function(){
var checkInventory = false, inventoryTimer;
function myTimerFunction() { /* ... */ }
function doSomething() { /* ... */ }
$(document).ready(function(){
checkInventory = true;
/* save handle to timer so you can cancel or reset the timer if necessary */
inventoryTimer = setTimeout(myTimerFunction, 5000);
});
})();
Encapsulate it:
function caller(delegate, persist){
delegate();
if(persist){
var timer = setInterval(delegate, 300);
return {
kill: function(){
clearInterval(timer);
}
}
}
}
var foo = function(){
console.log('foo');
}
var _caller = caller(foo, true);
//to stop: _caller.kill()