Call JavaScript function after 1 second One Time - javascript

I have successfully managed to make a div hide on click after 400 milliseconds using a setInterval function. My issue is that it runs continually, I only need the function to execute once. After a quick search I discovered that the setInterval can be stopped by clearInterval. Am I using this incorrectly? The closeAnimation function is being executed on click. I modelled my code after the code on this page: http://www.w3schools.com/jsref/met_win_setinterval.asp
function closeAnimation() {
setInterval(function(){hide()}, 400);
clearInterval(stopAnimation);
}
var stopAnimation = setInterval({hide()}, 400);

If it needs to run just once you can use setTimeout
setTimeout(function () {
console.log('Hello world')
}, 1000)
setTimeout(() => {
console.log('Foo bar')
}, 1000)

You should use setTimeout():
setTimeout(function() {
getScore();
getResult();
}, 1800000);
The '1800000' is the time in milliseconds after which you want this function to execute. In this case, 30 minutes.

Related

Set interval works only first time. Is there any solution?

I want to run the function continuously. But it only works first time properly. Is there any solution for working this function continuously?
$(document).ready(function() {
setInterval(() => {
$('#open-band').trigger('click');
setTimeout(() => {
$('#close-band').trigger('click');
}, 50000);
}, 15000);
});
If the code inside the setInterval takes longer than the time you have set it will create another process before the function finishes messing everything up. So choosing setTimeout is actually better.
To make a function loops in setTimeout use a following syntax:
function function1() {
// something here
}
function runner() {
function1();
setTimeout(function() {
runner();
}, time);
}
runner();
Given the comment under the question explaining your goal:
I want to trigger a button to show a div after 15 secs when the page is loaded, and 50 secs later another trigger for closing the div. & I want to run this continuously
I would suggest that you chain setTimeout() calls instead of using setInterval() which will cause the events to overlap and become a mess. I'd also suggest that you call show() and hide() directly on the required elements instead of faking click events in the DOM. Try this:
function openBand() {
$('#yourElement').show();
setTimeout(closeBand, 50000);
}
function closeBand() {
$('#yourElement').hide();
setTimeout(openBand, 15000);
}
$(document).ready(function() {
setTimeout(openBand, 15000);
// or just call closeBand() here directly, if the element starts as hidden
});
You should change your current function with this one
$(document).ready(function() {
setInterval(() => {
$('#open-band').trigger('click');
}, 15000);
setTimeout(() => {
$('#close-band').trigger('click');
}, 50000);
});

Do function with timeout while togglebutton is pressed

I want to run a function with a timeout of 2000 ms. The function should just run while toggleButton is pressed.
When I run this function my CPU explodes:
do {
setTimeout(function () {
me.pushMockData();
}, 2000);
}
while (liveButton.getPressed() != false);
Your CPU explode because you create Timeout again, again and again really fast in your loop when button is pressed. If you want to run your function every 2 second :
You should test if the the button is pressed.
Use setInterval
Inside setInterval, check if the button is still pressed, if not, clearInterval
https://www.w3schools.com/jsref/met_win_setinterval.asp
If you just want to active your function 2 second later, use setTimeout inside if.
You are going about this all wrong, keep things simple and attach an event listener to the button and call setTimeout then.
HTML
<button id="my_button">Click Me</button>
JavaScript
document.getElementById('my_button').addEventListener('click', function () {
setTimeout(function () {
alert('Clicked!');
}, 2000);
});
JSFiddle
Live Example
It's because you are constantly calling the setTimeout function in the while loop.
var timeout;
if (liveButton.getPressed())
{
if (typeof timeout !== 'undefined') {
timeout = setTimeout(function () {
me.pushMockData();
}, 2000);
} else {
clearTimeout(timeout);
}
}
If you can catch the onPress and onRelease event, it would be better if you do following
onPress
var myTimeout = setTimeout( ... , 2000 )
onRelease
clearTimeout(myTimeout)
example: https://jsfiddle.net/jfefL4oo/1/

setInterval after setTimeout

var playtop = setInterval(goright, 5000);
function goright(){
...
}
The above works.
Now, I need to interrupt the above by clicking on a button, do something on page, and ten seconds after click - activate the setInterval again.
$("#btngoright").click(function(){
clearInterval(playtop);
...
setTimeout(playtop, 10000);
});
But, once interrupted, setInterval is not activated again.
It's not working because playtop is the id that was returned when initially setting the interval.
The setTimeout method expects a function, not an id, therefore you should pass a reference to the goright function again:
setTimeout(goright, 10000);
If you want to activate the interval again after 10 seconds, you can set an interval and pass a reference to the goright function in an anonymous function:
$("#btngoright").click(function(){
clearInterval(playtop);
setTimeout(function () {
setInterval(goright, 5000);
}, 10000);
});
Nearly. It should be:
$("#btngoright").click(function(){
clearInterval(playtop);
setTimeout(function () {
playtop = setInterval(goright, 5000);
}, 10000);
});
This way you are putting control back into the playtop variable meaning that the interrupt function will work more than once.

Angular How to use $interval without delay during first run?

I have the following function which is animating some object on the screen:
$interval(function() {
$('#cloudLeftToRight').animate({
left: '+=250%',
}, 7000, function() {
$('#cloudLeftToRight').removeAttr('style');
$scope.resetAnimationCloudLeftToRight();
});
}, 8000);
Problem is that if app function is triggered first animation is displayed after the 8 sec. delay.
I would like to run animation immediately after the function is triggered and after that repeat animation each 8 sec.
It occurred to me one solution:
Make the timer and animation function separated and after init call only animation function and immediately call the timer function where should be passed name of the animation function.
Any better solution please?
Many thanks for any advice.
You could try something like this:
function myFunction(){
$('#cloudLeftToRight').animate({
left: '+=250%',
}, 7000, function () {
$('#cloudLeftToRight').removeAttr('style');
$scope.resetAnimationCloudLeftToRight();
});
}
myFunction();
$interval(function () {
myFunction();
}, 8000);
I think it looks cleanest to use $timeout and recursively call yourself in an immediately invoked function:
(function animate() {
$('#cloudLeftToRight').animate({
left: '+=250%',
}, 7000, function () {
$('#cloudLeftToRight').removeAttr('style');
$scope.resetAnimationCloudLeftToRight();
});
$timeout(animate, 8000);
})()
Maybe this pseudocode helps you
var runAnim = function () {
//here animation code
$timeout(runAnim, INTERVAL);
};
runAnim();

jQuery/JS infinite timed loop

I am trying to create a series of clicks on different elements on screen at different times. I can easily do this using the setTimeout function, but I need to make this an infinite loop!?
Here is a snippet of how I am currently handling the code.
setTimeout(function () {jQuery('.CR_1').trigger('click');}, 1000);
setTimeout(function () {jQuery('.CR_1').trigger('click');}, 5000);
setTimeout(function () {jQuery('.CR_2').trigger('click');}, 5500);
Any ideas on how I can make this work?
EDIT: Let me a little more clear. I am trying to run the set of functions in the same order over and over. The setInterval worked perfectly. I am super sorry for any confusion.
setInterval ( "flips ()", 12000 );
function flips (){
setTimeout(function () {jQuery('.CR_1').trigger('click');}, 1000);
setTimeout(function () {jQuery('.CR_1').trigger('click');}, 5000);
setTimeout(function () {jQuery('.CR_2').trigger('click');}, 5500);
}
Just call setTimeout from within your function.
setTimeout(callMe, 1000);
function callMe() {
jQuery('.CR_1').trigger('click');
setTimeout(callMe, 1000);
}
You could also use setInterval but I prefer doing it this way because it will be called 1000ms from the last run, not every 1000ms regardless of how long it takes to run (if the process is synchronous).
clicky()
function clicky() {
setTimeout(function () {jQuery('.CR_1').trigger('click');}, 1000);
setTimeout(function () {jQuery('.CR_1').trigger('click');}, 5000);
setTimeout(function () {jQuery('.CR_2').trigger('click');clicky()}, 5500);
}
i think you should use setInterval instead of setTimeout
Why not use setInterval instead?
var delayedFunctions = [
[1000,function(){ ... }],
[5000,function(){ ... }],
[5500,function(){ ... }]
];
var fIndex = 0;
function runDelayedFunctions(){
var details = delayedFunctions[fIndex];
setTimeout( function(){
details[1].call(this);
if (++fIndex >= delayedFunctions.length) fIndex=0;
runDelayedFunctions();
}, details[0] );
};
runDelayedFunctions();

Categories

Resources