So I have this code
function timer()
{
setTimeout(function(){alert("Out of time")}, 3000); //Alerts "Out of time" after 3000 milliseconds
}
function resetTime()
{
timer(); //this is not right, i thought it would override the first function but it just adds another timer as well which is not what I want
}
function stopTime()
{
//What could go here to stop the first function from fully executing before it hits 3000 milliseconds and displays the alert message?
}
the function timer() starts as the page loads but if I have a button for stopTime() and I click on it, how do I stop the first function from executing and stop it from hitting the 3000 millisecond mark and alerting "Out of time"?
Use a variable with scope over all of your functions.
var myTimer;
...
myTimer = setTimeout(...);
...
clearTimeout(myTimer);
var timer;
function timer()
{
timer = setTimeout(function(){alert("Out of time")}, 3000); //Alerts "Out of time" after 3000 milliseconds
}
function resetTime()
{
clearTimeout(timer);
timer(); //this is not right, i thought it would override the first function but it just adds another timer as well which is not what I want
}
function stopTime()
{
//What could go here to stop the first function from fully executing before it hits 3000 milliseconds and displays the alert message?
}
try this it will Work For you
Its best to use the useRef hook from React
import {useRef} from 'React';
const function =()=>{
const timerRef = useRef();
const timerFunction =()=>{
timerRef.current = setTimeout(()=>{
//Your Code
},5000);
`
const clearTimerFunction =()=>{
clearTimeout(timerRef.current);
}
}
The value returned from setTimeout is a unique ID that you can use later to cancel the timeout with clearTimeout.
var timeout;
function timer () {
timeout = setTimeout(/* ... */);
}
function resetTime() {
stopTime();
timer();
}
function stopTime() {
clearTimeout(timeout);
}
Related
i am running a setinterval function to check for a payment from coinbase in my react native app, i run the function after every 10 seconds, after the payment has been made, i clear the setinterval and navigate to the homepage, but still the setinteval keeps running how can i stop this?
useEffect(() => {
getData();
myinterval();
}, []);
const myinterval= () => setInterval(function () {
checkCharge();
}, 10000);
const stopCounter = () => {
clearInterval(myinterval);
}
const checkCharge = async () => {
try {
...SOME_CODE_HERE...
stopCounter()
navigation.navigate("HomeScreen");
} catch (e) {
console.log(e);
}
};
i ran into a similar problem some months back, this soluion should work perfectly:
const myinterval = setInterval(function () {
checkCharge();
}, 10000);
but in my case, since I store the setInterval in a variable instead of a function, I had some weird problems, like the setInterval might run three times or keep on running even after I used clearInterval(INTERVAL_NAME); so if you want to check if a payment has been made, create a button that would tell the user to click when they have made the payment, this would be a lot safer than to run the function inside of setInterval
I believe it's because myinterval is assigned to a function and not the actual return value of the setInterval() function. So try to change
const myinterval = () => setInterval(function () {
checkCharge();
}, 10000);
to
const myinterval = setInterval(function () {
checkCharge();
}, 10000);
and then canceling the myinterval variable with clearInterval(myinterval);
You aren't using the return from myinterval() to clear the setInterval. setInterval() returns an id that is used to clear the interval. When you call the function myinterval, it is returning that ID. What you need to do is store that ID in a variable that you can use to clear the interval.
...
function createInterval(){
return setInterval(checkCharge, 10000);
}
function stopCounter(id){
clearInterval(id);
}
...
var id = createInterval();
...
function checkCharge(){
try {
...
stopCounter(id);
...
} catch(e){
console.error(e);
}
}
I want repeat this code every 4 seconds, how i can do it with javascript or jquery easly ? Thanks. :)
$.get("request2.php", function(vystup){
if (vystup !== ""){
$("#prompt").html(vystup);
$("#prompt").animate({"top": "+=25px"}, 500).delay(2000).animate({"top": "-=25px"}, 500).delay(500).html("");
}
});
Use setInterval function
setInterval( fn , miliseconds )
From MDC docs:
Summary
Calls a function repeatedly, with a fixed time delay between each call to that function.
Syntax
var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
var intervalID = window.setInterval(code, delay);
where
intervalID is a unique interval ID you can pass to clearInterval().
func is the function you want to be called repeatedly.
code in the alternate syntax, is a string of code you want to be executed repeatedly. (Using this syntax is not recommended for the same reasons as using eval())
delay is the number of milliseconds (thousandths of a second) that the setInterval() function should wait before each call to func. As with setTimeout, there is a minimum delay enforced.
Note that passing additional parameters to the function in the first syntax does not work in Internet Explorer.
Example
// alerts "Hey" every second
setInterval(function() { alert("Hey"); }, 1000);
setInterval(function(){
// your code...
}, 4000);
It's not too hard in javascript.
// declare your variable for the setInterval so that you can clear it later
var myInterval;
// set your interval
myInterval = setInterval(whichFunction,4000);
whichFunction{
// function code goes here
}
// this code clears your interval (myInterval)
window.clearInterval(myInterval);
Hope this helps!
Another possibility is to use setTimeout, but place it along with your code in a function that gets called recursively in the callback to the $.get() request.
This will ensure that the requests are a minimum of 4 seconds apart since the next request will not begin until the previous response was received.
// v--------place your code in a function
function get_request() {
$.get("request2.php", function(vystup){
if (vystup !== ""){
$("#prompt").html(vystup)
.animate({"top": "+=25px"}, 500)
.delay(2000)
.animate({"top": "-=25px"}, 500)
.delay(500)
.html("");
}
setTimeout( get_request, 4000 ); // <-- when you ge a response, call it
// again after a 4 second delay
});
}
get_request(); // <-- start it off
const milliseconds = 4000
setInterval(
() => {
// self executing repeated code below
}, milliseconds);
Call a Javascript function every 2 second continuously for 20 second.
var intervalPromise;
$scope.startTimer = function(fn, delay, timeoutTime) {
intervalPromise = $interval(function() {
fn();
var currentTime = new Date().getTime() - $scope.startTime;
if (currentTime > timeoutTime){
$interval.cancel(intervalPromise);
}
}, delay);
};
$scope.startTimer(hello, 2000, 10000);
hello(){
console.log("hello");
}
simply I want to stop a function after specific time like 5 seconds from calling it.
I couldn't find a way to do it, can somebody help me
function popUp() {
// Do some Thing
});
popUp();
// how to stop popUp() after calling it after 5 seconds from calling it??
You can use setTimout to run a function after a set amount of time. For example:
setTimeout(hidePopup, 5000);
Will run the below function after 5 seconds (5000 milliseconds):
function hidePopup() {
// Do the opposite
}
Just use return statement:
function popUp() {
// Do some Thing
//Timer simulator
for (i = 0; i < 100; i++) {
if (i == 99) return
}
});
How about you call your function, and then call setTimeout inside your function after 5 seconds to change display to "none", like this:
function popUp() {
// Do some Thing
// SetTimeout to change display to none
setTimeout(function () {
document.getElementById('div-id').style.display = "none";
}, 5000);
});
popUp();
I saw the snippet below that validates an input field after every user change, but it waits for 1, 5 seconds of user inactivity before it actuallyt starts validating:
var timer;
var inputElement = document.getElementById("nameInput");
inputElement.oninput = function()
{
delayedInputValidation(validateInput, 1500);
};
function delayedInputValidation(func, delayInMilliseconds)
{
clearTimeout(timer);
timer = setTimeout(func, delayInMilliseconds);
}
function validateInput()
{
... //stuff here
}
My questions is not about input validation, but about the timeout mechanism. I tried to generalize the delay function to make it work for arbitrary functions:
function delayedFunction(timer, func,delayInMilliseconds)
{
clearTimeout(timer);
timer = setTimeout(func, delayInMilliseconds);
}
The point is that you have several timers in your JavaScript, for example:
var inputTimer;
var otherTimer;
...
And if you pass along the same timer, the delay function woul clear (reset) the correct timer and then set it again using the setTimeout function.
However, this doesn't work because the timer object is passed in a reference-by-value way (discussion here), resulting in the local variable timer to be changed, but not the actual inputTimer.
How can I fix this method?
You can use something like
var timers = {};
function delayedFunction(timer, func, delayInMilliseconds) {
clearTimeout(timers[timer]);
timers[timer] = setTimeout(func, delayInMilliseconds);
}
delayedFunction('inputTimer', func1, delay1);
delayedFunction('otherTimer', func2, delay2);
Or like this:
var timers = [],
inputTimer = 0,
otherTimer = 1;
function delayedFunction(timer, func, delayInMilliseconds) {
clearTimeout(timers[timer]);
timers[timer] = setTimeout(func, delayInMilliseconds);
}
delayedFunction(inputTimer, func1, delay1);
delayedFunction(otherTimer, func2, delay2);
I have this code:
var int1 = setInterval(function () {
// do stuff
if(//stuff done){
clearInterval(int1);
setTimeout(
function () {
setInterval(int1)
}
,60000);
}}
}, 1000)
and want the interval to be running again after 60 seconds but setInterval(int1) doesn't seem to trigger it again. What am I doing wrong?
EDIT: full code: http://pastie.org/8704786
That'd because int1 is not a function, but an interval id. Try this instead:
var int1;
var func = function () {
// do stuff
if(//stuff done){
clearInterval(int1);
setTimeout(func, 60000);
}
};
int1 = setInterval(func, 1000);
You did 2 mistakes:
setInterval whant a function, while int1 contains an interval handle
You didn't pass amount of time in your setInterval call
What you want probably is:
var int1;
function scheduleStuff() {
int1 = setInterval(doStuff, 1000);
}
function doStuff() {
// do stuff
if(/*stuff done*/){
clearInterval(int1);
setTimeout(scheduleStuff,60000);
}}
}
scheduleStuff();
set intervall expectes a function wich is called after waiting time...
this line is wrong:
setInterval(int1)
no function and no waiting time given...