Javascript/jQuery setInterval shown old value onclick re-call function - javascript

I'm working with setInterval function to replace text.
function loadData(set){
if(set == undefined){
var a = "Hello";
}
else{
var a = set;
}
setMe(a);
function setMe(val){
setInterval(function(){
$(".setMe").html(val);
}, 1000);
}
}
loadData();
$('#clickMe').on('click', function(){
loadData("Good");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="setMe"></div>
<button id="clickMe">Click Me</button>
When I try to click the button, it will change the text to be Good. But why the old text is still shown alternate with Hello? You can try on the demo.
What I want is replace the text only to be Good.

You're calling loadData which starts the first interval setting the text to "Hello". Then when you're clicking the button, it starts another interval which sets the text to "Good". The problem is that you now have 2 intervals both setting the text value. The intervals will both keep running forever.
What you need is to use setInterval instead, which will only delay the change of the text value, instead of repeatedly changing it.
function loadData(set){
if(set == undefined){
var a = "Hello";
}
else{
var a = set;
}
setMe(a);
function setMe(val){
setTimeout(function(){
$(".setMe").html(val);
}, 1000);
}
}
loadData();
$('#clickMe').on('click', function(){
loadData("Good");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="setMe"></div>
<button id="clickMe">Click Me</button>

setInterval is for running function repeatedly at regular interval, unless cleared.
What is happening :
You are calling your function twice and hence two intervals are running. One setting the value to Hello and other setting the value to Good.
You can replace this with setTimeout, which runs a function once, after a delay.
function loadData(set){
if(set == undefined){
var a = "Hello";
}
else{
var a = set;
}
setMe(a);
function setMe(val){
setTimeout(function(){
$(".setMe").html(val);
}, 1000);
}
}
loadData();
$('#clickMe').on('click', function(){
loadData("Good");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="setMe"></div>
<button id="clickMe">Click Me</button>

You need to change where variable a is declared
And also setInterval is unnecessary here as you want to fire your action only once (and setInterval is repeated).
function loadData(set){
var a;
if(set == undefined){
a = "Hello";
}
else{
a = set;
}
function setMe(val){
setTimeout(function(){
$(".setMe").html(val);
}, 1000);
}
setMe(a);
}
loadData();
$('#clickMe').on('click', function(){
loadData("Good");
});

Related

How to make a toggle variable persist?

I'm working on a quiz page where I have a timer that I would like to be able to toggle on or off so it doesn't distract the user, and save the setting after submitting an answer. The timer function works, and calls on localStorage.getItem(). But when I try the below with a boolean to see if the showHideTimer() button is clicked, the timer always shows up when the next question appears. The console always logs true when the page loads a new question.
<script>
var clickCookie = 'clicked';
var clicked = localStorage.getItem(clickCookie);
console.log(clicked);
function showHideTimer(){
if(clicked==true){
document.getElementById("testHeaderRight").style.color = "black";
clicked=false;
localStorage.setItem(clickCookie, clicked);
console.log(clicked);
return clicked;
}
else{
document.getElementById("testHeaderRight").style.color = "white";
clicked=true;
localStorage.setItem(clickCookie, clicked);
console.log(clicked);
return clicked;
}
};
window.onload = function(){
if(clicked===null){
localStorage.setItem(clickCookie, false);
} else {
showHideTimer(clickCookie);
}
};
</script>
<body>
<button id="showHideTimer" onclick="showHideTimer()">Toggle Timer</button>
<div id="testHeaderRight">
Time Remaining :
<span id="time"></span>
</div>
<script>
var cookieName = 'startTimer';
var savedSeconds = localStorage.getItem(cookieName);
function startTimer(duration, display) {
var timer = duration, seconds;
setInterval(function () {
seconds = parseInt(timer);
display.textContent = secondsToHms(seconds);
var runningTime = (parseInt(seconds));
localStorage.setItem(cookieName, runningTime);
}, 1000);
}
window.onload = function () {
var startTime = 7200,
display = document.querySelector('#time');
if (savedSeconds === null){
startTimer(startTime, display);
} else {
startTimer(savedSeconds, display);
}
};
</script>
</body>
I've tried moving the window.onload call into the same function as the timer since that is functioning properly, but seems to make no difference. I've tried switching the clicked=true/false; variables around to make sure I'm not confusing myself with booleans, and they switch freely in the console when clicking on the button. I've tried changing the return value of the showHideTimer() function to be localStorage.setItem(clickCookie, clicked);
When you get the item out of storage it's a string, "true", not a boolean.
So your if(clicked==true) comparison never passes and you end up on the "false" path every time.

Function inside event listener triggers only on it's initialization

var init = true;
$('#btn').on('click', delay(function() {
$('#text').append('click');
init = false;
}, 100));
function delay(fn, ms, enabled = true) {
$('#text').append(init);
// if(init) disable delay
let timer = 0;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(fn.bind(this, ...args), ms || 0);
}
}
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<button id='btn'> TRIGGER </button>
<div id="text"></div>
Init is a global variable which is meant to be used inside delay function to disable delay (init true/false) only on event listener initialisation.
The problem is that the delay function is triggered only once and ignores the change (to false) of the init variable.
For example, try clicking the trigger button. The init variable value is printed only for the first time.
You are calling the delay function in a wrong way in the click handler. You have to call it like so:
$('#btn').on('click', function () {
delay(function() {
$('#text').append('click');
init = false;
}, 100);
});
You will have to check for the value of init inside the function, like this:
$('#btn').on('click', delay(function() {
if(init) {
$('#text').append('click');
init = false;
}
}, 100));
At the moment I don't know why append is not working but with a little workaround you can obtain what you want. Concatenate the original text and the actual one and use text() to set it again:
var init = true;
$('#btn').on('click', function() {
$('#text').text(init);
setTimeout(myDelay, 5000);
});
function myDelay() {
let originalText = $('#text').text();
init = false;
console.log("init is false");
console.log("original text displayed: " + originalText);
$('#text').text(originalText + " " + init);
}
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<button id='btn'> TRIGGER </button>
<div id="text"></div>

Javascript clicked and not been clicked for 4 seconds

I have a question about my code. What I'm trying to do is if a certain button is clicked and it isn't clicked again within 4 seconds, a element will be showed and another element hide. But if it is clicked within 4 seconds, it stays the same and so on. I think I should use SetInterval() and ClearInterval(). Currently I have two other functions that do other things. Maybe I can my function there?
Hopefully I have made it clear.
Current javascript code:
var clicks = 0;
function clicks5times() {
clicks = clicks+1;
if(clicks == 6){
document.getElementById('scherm3').style.display = 'block';
document.getElementById('scherm2.2').style.display = 'none';
}
}
var clicked = false;
setInterval(function(){
if (!clicked) {
document.getElementById("scherm4").style.visibility = "visible";
document.getElementById("scherm2.2").style.visibility = "hidden";
}
},13000);
document.getElementById("buttontimer").addEventListener("click", function(){
clicked = true;
});
Rather than set interval, I would say a timer would be better. Eg:
var clickTimer;
function startTimer() {
clickTimer = window.setTimeout(function(){
document.getElementById("scherm4").style.visibility = "visible";
document.getElementById("scherm2.2").style.visibility = "hidden";
},4000);
}
function stopTimer() {
window.clearTimeout(clickTimer);
}
function restartTimer() {
stopTimer();
startTimer();
}
document.getElementById("buttontimer").addEventListener("click", function(){
restartTimer();
});
This way when you want to stop the timer or start the timer, you have to just call above functions for other scenarios.
eg:
If you have an init function:
function init() {
...
//some code
startTimer();
}
And maybe call stop timer like so:
function clicks5times() {
...
stopTimer();
}
Split your event handlers in two different functions (eg firstClick and secondClick). The first handler should just add a second event listener and remove it after 4 seconds. For this one-off task, use setTimeout instead of setInterval as you need the task to be done only once after 4 seconds and not every 4 seconds. So I would proceed as follows:
var secondClick = function() {
// DO WHATEVER YOU WANT TO HAPPEN AFTER THE SECOND CLICK
}
var firstClick = function() {
// DO WHATEVER YOU WANT TO HAPPEN AFTER THE FIRST CLICK
document.getElementById("buttontimer").addEventListener("click", secondClick);
setTimeout(function() {
document.getElementById("buttontimer").removeEventListener("click", secondClick);
}, 4000);
};
buttonElement.addEventListener("click", firstClick);
in Javascript
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body>
<button id="buttontimer">fghfgh</button>
</body>
</html><!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body>
<button id="buttontimer">fghfgh</button>
<script>
document.getElementById('buttontimer').onclick = function(){
document.getElementById("buttontimer").disabled=true;
setInterval(function(){
if (document.getElementById("buttontimer").disabled == true) {
document.getElementById("buttontimer").disabled = false;
}
},10000);
};
</script>
</body>
</html>
and Jquery
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var button = $('<button>Click Me</button>');
button.clicked = false;
$('body').append(button);
var clicked = false;
button.click(function(){
button.clicked = true;
button.prop('disabled', true);
clicked = true
setInterval(function(){
if (clicked) {
button.prop('disabled', false);
}
},10000);
});
});
</script>
</head>
<body>
</body>
</html>
once u click button disable the property after the timer finish enable back the property

Java script : How to find setInterval function is now running or timedout?

In my project I use two setInterval functions, One function is running all time. The second function is start and stop dynamically according to keyboard input. How to find state(Running or Timeout) of second setInterval funcion?
setInterval(function()
{
if(//want to check state of seInterval Function fire)
{
//somecode
}
},300);
var fire=setInterval(function()
{
// some code
},300);
Better add a boolean variable isRunning to the methods in setInterval. Toggle the value according to it. Using the value you can track the status.
Based on the code you have posted:
isFirstInstanceRunning =true;
isSecondInstanceRunning = false;
setInterval(function() {
//want to check state of seInterval Function fire
if(isFirstInstanceRunning){
//somecode
}
},300);
//--- Pass a boolean parameter as "true" onKeypress
function startSecondInstance(toCheck) {
var fire=setInterval(function() {
//want to check state of seInterval Function fire
if(toCheck){
//somecode
}
},300);
}
//---Similarly when you stop the second method
function stopSecondInstance() {
clearInterval(fire);
isSecondInstanceRunning = false;
}
No, not directly, however you could set a variable to check on periodically to see if it's running:
var isRunning = false;
//Start it
var timer = setInterval(function() {
//yada yada function stuff
isRunning = true;
}, 3000);
//Check it
if (isRunning) console.log("Running!");
//Stop it
clearInterval(timer);
isRunning = false;

How do I make a function to run only when the mouse is NOT hovering a specified div?

what I got now is:
function()
{
setInterval("getSearch()",10000);
getSearch();
}
);
But I want this interval to pause if the mouse cursor is placed inside a div on my website. How do I attack this problem? Surely I need to give the div an ID.. But some input on how to make the javascript/jquery part is much appreciated.
EDIT: More of my code.. I'm not quite sure where to insert the code in the answers inside this:
$(
function()
{
setInterval("getSearch()",10000);
getSearch();
}
);
TwitterCache = {};
function getSearch()
{
var url = "http://search.twitter.com/search.json?q=test&refresh=6000&callback=?"; // Change your query here
$.getJSON
(
url,
function(data)
{
if( data.results ) // Checks to see if you have any new tweets
{
var i = -1, result, HTML='', HTML2='';
while( (result = data.results[++i]) && !TwitterCache[result.id] )
{
insert html.. blabla}
setInterval returns a "reference" to that interval you set up, allowing you to stop it with window.clearInterval(), and that's what you have to do:
var myInterval;
function startMyInterval() {
if (!myInterval) {
// It's better to call setInterval width a function reference, than a string,
// also always use "window", in case you are not in its scope.
myInterval = window.setInterval(getSearch, 10000);
}
}
function stopMyInterval() {
if (myInterval) {
window.clearInterval(myInterval);
}
}
startMyInterval(); // Start the interval
jQuery("#myDiv").hover(stopMyInterval, startMyInterval);
Set a global variable
var intID;
Assign setInterval to this variable
intID = setInterval("getSearch()",10000);
Set an id for the div
$("#divid").hover(function(){
clearInterval(intID);
},
function(){
// set the interval again
});
I think this should work:
$("#divID").hover(
function () {
PauseTheInterValThing()
},
function()
{
setInterval("getSearch()",10000);
getSearch();
}
);
The simplest way, and the shortest
Simplest method would be:
<div id="yourDiv">
EXAMPLE TEXT
</div>
<script language="Javascript">
var interval = setInterval("getSearch()",1000);
document.getElementById("yourDiv").addEventListener('mouseover', function()
{
clearInterval(interval);
},false);
document.getElementById("yourDiv").addEventListener('mouseout', function()
{
interval = setInterval("getSearch()",1000);
},false);
</script>
insert this in your dom-ready function:
var inv = setInterval("getSearch",1000);
$('#yourdiv').mouseover(function(){
clearInterval(inv);
}).mouseout(function(){
inv = setInterval("getSearch",1000);
})

Categories

Resources