I'm new to Jquery and I want to change the 2000 while the code is running
var interval = setInterval(function() {
//do something
}, 2000);
Something like this:
var wait = 200;
var interval = setInterval(function() {
if(wait == 200)
{
wait = 100;
}
}, wait);
Is there a way of doing this?
You can stop the loop
clearInterval(interval);
And start over with the new time:
interval = setInterval(fn, newTime);
Related
I have a simple javascript function that loads on document ready:
var start = 1;
var speed = 1000;
$(document).ready(function () {
go();
setInterval(function () {
go();
}, speed);
This is the function in details:
function go() {
$("#score").html(start.toLocaleString());
start += 1;
}
This is basically a counter which starts from number 1 to infinite, at 1000 milliseconds speed. Here is the thing , now: I have another function:
function modify() {
speed = 500;
}
which regulates the setIntval speed on the main function. The problem is it applies on page refresh only. How do I update it in real time without refreshing page?
You can't update the current one, you have to stop it and set a new timer, which does the same but with a different delay.
var speed = 1000;
var start = 1;
function go() {
$("#score").html(start.toLocaleString());
start += 1;
}
function startGoTimer(){
return = setInterval(function () {
go();
}, speed);
}
function modifyTimer( previousTimer, newDelay=500) {
clearInterval(previousTimer);
speed = newDelay;
startGoTimer();
}
var timer = startGoTimer();
// Some code
modifyTimer(timer, 500);
For fun I just tested what would hapopen if you just change the time:
var timing = 1000;
var interval = setInterval(function(){console.log("test")}, timing);
// Now we get a log every 1000ms, change the var after some time (via console):
timing = 10;
// still an interval of 1000ms.
A really simple solution is to make use of the setInterval's parameters,
var intervalID = scope.setInterval(func, delay[, param1, param2, ...]);
and also pass the speed as param1.
Then, at each interval, check if it changed, and if, clear the existing timer and fire up a new.
Stack snippet
var start = 1;
var speed = 1000;
var timer;
$(document).ready(function() {
go();
timer = setInterval(function(p) {
go(p);
}, speed, speed);
// for this demo
$("button").click(function(){ speed = speed/2});
})
function go(p) {
if(p && p != speed) {
clearInterval(timer);
timer = setInterval(function(p) {
go(p);
}, speed, speed);
}
$("#score").html(start.toLocaleString());
start += 1;
}
div {
display: inline-block;
width: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="score">0</div>
<button>Modify</button>
I was asked in a phone interview to replicate Javascript's setInterval, clearInterval methods by writing my own. I am not allowed to use setTimeout or clearTimeout.
function setInterval(func, wait){
var currentTime = Date.now();
while(currentTime < wait){
currentTime = Date.now() - currentTime;
}
if(currentTime >= wait) {
func();
}
}
function clearInterval(myVar){
myVar = undeclared;
}
function setTimeout(func, ms, ...args){
const start = Date.now();
(function check(){
if(start + ms >= Date.now()){
func(...args);
} else {
requestAnimationFrame(check);
}
})()
}
You might use a pseudorecursive function and requestAnimationFrame to do this. Based on this setTimeout implementation without window.setTimeout you cane easily implement a new setInterval ...
PS: in node you can use process.nectTick instead of requestAnimationFrame
Another possibility is, taking example from here, the usage of Web Workers:
let mySetInterval = function(callback, timeout) {
let blob = new Blob([ "self.addEventListener('message', function(e) { \
let old_date = Date.now(); \
while (Date.now() - old_date <= " + timeout + ") {}; \
self.postMessage(true); \
}, false);" ], { type: "text/javascript" });
let worker = new Worker(window.URL.createObjectURL(blob));
worker.addEventListener("message", function(e) {
if (callback() === false) {
return
}
mySetInterval(callback, timeout)
}, false);
worker.postMessage(true);
};
var a = 0;
mySetInterval(() => { if (a >= 10) { return false } else { console.log(a++) } }, 1000)
console.log(45);
Every 1 second it updates the variable a with +1.
Like you see, in this way it is non-blocking and it will stop when the variable a is 10.
To clear the "interval", in this case simply return false inside the callback. Obviously is not the same as the clearInterval function! Here there is not something like an ID such as for the setInterval function.
Hard Task, you can sort of do what setInterval and setTimeout do with requestAnimationFrame ? Not the same, but could do what you want to do.
var time;
function repeatOften() {
$("<div />").appendTo("body");
time = requestAnimationFrame(repeatOften);
}
$("#start").on("click", function() {
time = requestAnimationFrame(repeatOften);
});
$("#stop").on("click", function() {
cancelAnimationFrame(time);
});
this is my code, which works but i don't know how to clear timeout and clearinterval
setTimeout(function(){
setInterval( function(){
if (Math.random()> 0.1){
countdown.extendTimer(-3)
console.log("im dying")
}
}, 1000)
}, 10000)
this is what i have tried, but the diseaseInterval() just starts immediately without waiting for 5 sec
function diseaseInterval(){
if (Math.random()> 0.1){
countdown.extendTimer(-3)
console.log("im dying")
}
}
function diseaseTimeout(){
setInterval( diseaseInterval(),1000)
}
var onDisease = setTimeout(diseaseInterval(),5000)
This time i tried clearInterval inside clearTimeout itself, but it still doesn't work
var onDisease = setTimeout(function(){
disease = true;
var diseaseInterval = setInterval( function(){
if (Math.random()> 0.1){
countdown.extendTimer(-3)
console.log("im dying")}
else if (disease=false) {
clearInterval(diseaseInterval);
}
}, 1000)
}, 10000)
function cure(){
clearTimeout(onDisease);
disease = false
}
I'm trying to create a simple countdown timer. It counts down from the number entered.
However, I'm trying to clear the interval when the counter gets to 0. At the moment it seems to acknowledge the if statement, but not clearInterval().
http://jsfiddle.net/tmyie/cf3Hd/
$('.click').click(function () {
$('input').empty();
var rawAmount = $('input').val();
var cleanAmount = parseInt(rawAmount) + 1;
var timer = function () {
cleanAmount--;
if (cleanAmount == 0) {
clearInterval(timer);
}
$('p').text(cleanAmount);
};
setInterval(timer, 500);
})
You're not saving the return value of the call to setInterval, which is the value that needs to be passed to clearInterval. Passing the timer handler does no good.
var timer, timerHandler = function () {
cleanAmount--;
if (cleanAmount == 0) {
clearInterval(timer);
}
$('p').text(cleanAmount);
};
timer = setInterval(timerHandler, 500);
I have a code in my js file.
function makeScrollable(wrapper, scrollable){
...
// Hide images until they are not loaded
scrollable.hide();
var loading = $('<div class="loading">Loading...</div>').appendTo(wrapper);
// Set function that will check if all images are loaded
var interval = setInterval(function(){
var images = scrollable.find('img');
var completed = 0;
if (completed == images.length) {
clearInterval(interval);
// Timeout added to fix problem with Chrome
setTimeout(function(){
loading.hide();
....
}, 1000); //end of setTimeout(func, delay)
} //end of if (completed == images.length)
}, 100); //end of var interval = setInterval(fn, 100)
...
}
(function(){
makeScrollable("div.sc_menu_wrapper", "div.sc_menu");
})(jQuery);
But my timeout function isn't calling. I am still getting the loading Div. Function should be call after 1 sec, which hide the loading div and execute code after. But it isn't happening. What i am doing wrong?
Thanks
Wrong position of code.
var completed = 0;
if (completed == images.length) { // This will be true only when there are no images
clearInterval(interval);
setTimeout(function(){
loading.hide();
....
}, 1000);
}
put it outside
var completed = 0;
var interval = setInterval(function(){
var images = scrollable.find('img');
if (completed == images.length) {
clearInterval(interval);
// Timeout added to fix problem with Chrome
setTimeout(function(){
loading.hide();
....
}, 1000); //end of setTimeout(func, delay)
} //end of if (completed == images.length)
}, 100); //end of var interval = setInterval(fn, 100)
And hope you are incrementing completed somewhere in the code