settimeout being ignore, function is called instantly - javascript

function ShowColoursScreen() {
setSquaresList()
$("#ModeOne").hide();
$("#ModeTwo").show();
setTimeout(function () {
$("#ModeOne").show();
$("#ModeTwo").hide();
setTimeout(function () {
ShowColoursScreen();
}, 1500);
}, 15000);
}
This is very very weird, Im wanting to rotated between two divs every 15 seconds (i dont want to use js intervals). However after the first fifteen seconds ShowColoursScreen(); runs without waiting the second 15 seconds (if that makes sense). Its like the timeout gets ignored, any ideas?

Your code is correct. However, the inner timeout just waits for 1.5 seconds as you forgot a zero. Simply replace the 1500 with 15000.
You can also simplify the call a bit - as you do not have any arguments there is no need for the anonymous function: setTimeout(ShowColoursScreen, 15000);

function ShowColoursScreen($elements) {
if(!$elements instanceof jQuery) {
$elements = $($elements);
}
var current = 0;
// What does this function do?
setSquaresList();
function showCurrent () {
var $currentElement = $($elements[current]);
$elements.not($currentElement).hide();
$currentElement.show();
(current++) % $elements.length;
setTimeout(showCurrent, 15000);
}
showCurrent();
return $elements;
}
ShowColoursScreen('#ModeOne, #ModeTwo')

Related

setTimeout inside setInterval does not work well

My code should change the class of the item in every second and repeat it forever.
function myFunction() {
setInterval(function() {
$("#item").addClass("class-one").removeClass("class-two");
setTimeout(function(){
$("#item").addClass("class-two").removeClass("class-one");
}, 1000);
},1000);
}
myFunction();
First time the code works well, but after the loop starts again, it starts switching very fast. Can anybody tell me why?
The interval starts
1 second later the interval resolves:
classes are switched over
the timeout is triggered
1 second later:
The timeout resolves
classes are switched over
The interval resolves
classes are switched over
the timeout is triggered
You probably want the timeout time to be half the interval time, not the same as it.
A better approach entirely would be to use one class and use jQuery().toggle to toggle it on and off every second (using one interval and no timeouts).
correct way :
var i = 0;
function myFunction() {
setInterval(function() {
if(i % 2 == 0) {
$("#item").addClass("class-one").removeClass("class-two");
} else {
$("#item").addClass("class-two").removeClass("class-one");
}
i++;
},1000);
}
myFunction();
or with your solution : ( increase 1 second of setInterval time )
function myFunction() {
setInterval(function() {
$("#item").addClass("class-one").removeClass("class-two");
setTimeout(function(){
$("#item").addClass("class-two").removeClass("class-one");
}, 1000);
},2000);
}
myFunction();

How would I make this function repeat? [duplicate]

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");
}

Looping a script every x seconds

I'm wondering how to loop a script every x seconds. I'm relatively new to javascript and jquery, however I do know how to use some of it in HTML.
I'm trying to make this script run every 34 seconds, however I don't know how to loop it as such.
Here's my script:
function byId(id){
return document.getElementById(id)
}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt) {
setTimeout(function() {
byId('audioID').play()
}, 13000);
}
However I don't know how I would loop this every 34 seconds, after it starts at 13 seconds.
Thanks!
setTimeout makes the script run after x miliseconds, if you want to run the script multiple times, you need to use setInterval instead.
setInterval( function(){ byId('audioID').play() }, 34000 );
If I understand correctly, you want to start the interval after 34 seconds, so you need to do this instead:
setTimeout(function(){
//Declaring the function within this code scope just for DRY purposes
var runFn = function(){
byId('audioID').play();
}
runFn(); //runs the function once before the interval starts.
setInterval(runFn, 34 * 1000 );
}, 13 * 1000);
Create a new function who will execute byId('audioID').play() every 34Secs
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt) {}
function byId(id) {
console.log(id);
return document.getElementById(id);
}
const loopTime = 34000; //34000 ms = 34secs
var startProcess = function() {
setInterval(function() {
byId('audioID').play();
}, loopTime);
};
setTimeout(startProcess, 13000);
This works. If you need to stop the interval just call clearInterval(interval).
var interval;
setTimeout(function(){
console.log("Started interval after 1 sec");
interval = setInterval(function(){
console.log("hai")},2000)
},1000);

javascript timer counting very fast as time passes

I want a counter which reset in specific interval of time. I wrote this code. When I refresh the page it is executing perfectly. But as time passes the timer goes really fast, skipping seconds. Any idea why this is happening.
function countdown_new() {
window.setInterval(function () {
var timeCounter = $("b[id=show-time]").html();
var updateTime = eval(timeCounter) - eval(1);
$("b[id=show-time]").html(updateTime);
if (updateTime == 0) {
//window.location = ("ajax_chart.php");
$("b[id=show-time]").html(5);
clearInterval(countdown_new());
// countdown_new();
//my_ajax();
}
}, 1000);
}
window.setInterval(function () {
countdown_new();
}, 5000)
HTML
Coundown in 5 seconds
The issue is because you are not clearing the previous timer before starting a new one, so you start a new one for each iteration. To clear the timer you should save a reference to it, and pass that to clearInterval, not a function reference.
Also, note that your pattern of using multiple intervals for different operations can lead to overlap (where two intervals are acting at the same time and cause odd behaviour). Instead, use setTimeout for the initial 5 second delay and then chain further calls to stop this overlap.
Try this:
var timer;
function countdown_new() {
timer = setInterval(function () {
var $showTime = $("#show-time")
var updateTime = parseInt($showTime.text(), 10) - 1;
$showTime.html(updateTime);
if (updateTime == 0) {
$showTime.html('5');
clearInterval(timer);
setTimeout(countdown_new, 5000);
}
}, 1000);
}
setTimeout(countdown_new, 5000);
Example fiddle
Note that you should use the # selector to select an element by its id attribute, and you should never use eval - especially not for type coercion. To convert a value to an integer use parseInt().
You are calling window.setInterval(), which schedules a function call to countdown_new() ever 5 seconds without stop.
Compounding the problem, you are calling countdown_new() again inside your clear interval.
You need to call setInterval just once to continuously execute a function every 5 seconds.
If you want to cancel an interval timer, you need do to this:
var intervalObj = setInterval(function() { ... }, 5000);
clearInterval(intervalObj);
Yes clearinterval does the trick.
function countdown_new(){
t = window.setInterval(function() {
var timeCounter = $("b[id=show-time]").html();
var updateTime = eval(timeCounter)- eval(1);
$("b[id=show-time]").html(updateTime);
if(updateTime == 0){
//window.location = ("ajax_chart.php");
$("b[id=show-time]").html(5);
clearInterval(t);
// countdown_new();
my_ajax();
}
}, 1000);
}

Repeat code every 4 seconds

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");
}

Categories