Uncaught TypeError: NaN JavaScript Sharepoint - javascript

I have developed a JavaScript countdown timer; also I have a SharePoint list that retrieves the minutes for countdown and its column name is Koha
I am retrieving Koha and initializing in a variable; But when I try running the app the countdown timer shows me NaN?
This is how I am retrieving Koha field:
function Retrieve(){
currentQuizItem = quizList.getItemById(quizID);
var quizName;
context.load(currentQuizItem);
var koha = currentQuizItem.get_fieldValues()["koha"];
//even if I try to convert it to number it does not work
koha = parseInt(Koha);
alert(koha); // here I can see my value but later when I initialize this var to countdown it says NaN;
}
This is my JavaScript countdown timer
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var fiveSec = 60 * koha, //If I make this 60 * 20 it works and there are 20 min to countdown
display = document.querySelector('#UItimer');
startTimer(fiveSec, display);
};
Now when I run my app if shown me NaN:NaN instead of showing me timer
please help me

Most likely you are getting this error since the SP.ClientContext.executeQueryAsync method is missing. The specified method is mandatory, it submits the pending query on the server, without it the line
var koha = currentQuizItem.get_fieldValues()["koha"];
returns undefined.
Here is a generic example for getting list item
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle(listTitle);
var item = list.getItemById(itemId);
ctx.load(item);
ctx.executeQueryAsync(
function(){
var val = item.get_fieldValues()[fieldName];
//...
},
function(sender,args){
console.log(args.get_message());
});

Related

How do you escape out of an alert box and resume flow of action? - Javascript

So i am writing a simple javascript timer, and at 30 seconds it prompts the user with an alert box if they would like to reset the count down or let it continue.
I am able to reset the timer however I get stuck when the user clicks cancel on the alert box.
I tried letting the timer just resume at its current time but that doesn't help as the alert box just keeps reappearing
I am still very new to javascript so I would like to stay using vanilla js till I get a deeper understanding of the fundamentals!
Any guidance would be greatly appreciated!
Heres my code:
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if(timer<30){
var message = confirm("Would you like to extend timer?");
if (message == true) {
timer = 60 * 1;
}
else{
timer = timer;
}
}
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
function resetTimer() {
timer = 60 * 1;
}
window.onload = function () {
var fiveMinutes = 60 * 1,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
just put if(timer==30) instead of if(timer<30) so that exactly at count of 30 units of time, you get asked once for confirmation at that instance (However be aware that until the confirmation is done, prompts will keep popping up every second). if you extend it, it will again wait till your timer goes down to 30 unit, else it will simply go down to 0 and break out.
function startTimer(duration, display) {
var timer = duration,
minutes,
seconds;
function timerFunc() {
timer -= 1;
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (timer == 30) {
var message = confirm("Would you like to extend timer?");
if (message == true) {
timer = 60;
} else return alert("Your timer has been stopped.")
}
setTimeout(timerFunc, 1000);
}
timerFunc();
}

Java Script Count Down Timer resets whenever page refreshes

I have PHP page, where I added a countdown for 30 min. and as it ticks when I refresh the page or perform a query of 'insert' and redirect back to that page, the timer gets reset.
I want the timer to be constant and continue count without any interruptions when the page gets refreshed.
My code goes as:
function startTimer(duration, display) {
var timer = duration,
minutes, seconds;
setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function() {
var fiveMinutes = 60 * 30,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="timer">
<div>Section</div>
<div class="time">
<strong>Time left: <span id="time">30:00</span></strong>
</div>
</div>
Any Help Is Appreciated..
Use html5 local storage to update the timer value and when page load occurs read the timer value from local storage. I guess no other way.
Whenever your PHP page loads, the javascript is loaded with it. So
window.onload = function () {
var fiveMinutes = 60 * 30,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
is called and the timer starts at 5 minutes.
One solution would be to do an Ajax request in window.onload and get the remaining time.
Another solution would be to set the fiveMinutes variable (obviously it should be renamed more appropriately) via PHP, if the javascript code is inside your PHP file, like
<script>
...
var timeLeft = <?php echo $timeLeft ?>;
...
</script>
The first solution is the standard way to go and the second one is the easy way to go.
As others have pointed out, you could use local storage (if the your target clients support this feature see here)
<script>
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
timer = --timer;
if (timer >= 0) {
localStorage.setItem('time', timer);
//timer = duration;
}
}, 1000);
}
window.onload = function () {
var countDown = 60 * 30;
var oldVal = localStorage.getItem('time');
if (oldVal && oldVal > 0) {
countDown = oldVal;
}
var display = document.querySelector('#time');
startTimer(countDown, display);
};
</script>
edit: of course one must not forget to check whether the stored value is below zero.
As already pointed out, you could store the current time with localStorage.
To do so you would save both minutes and seconds in each interval tick:
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
localStorage.setItem("minutes", minutes); // <--
localStorage.setItem("seconds", seconds); // <--
And in the load function you'd read from them and set the starting value appropriately. It's important to note that values are always stored as strings, and as such, it would be necessary to parse them back to numbers before passing them through:
window.onload = function () {
var timeLeft = 60 * 30,
display = document.querySelector('#time');
var minutes = localStorage.getItem("minutes"); //read minutes
var seconds = localStorage.getItem("seconds"); //read seconds
if (minutes && seconds){
timeLeft = Number(minutes) * 60 + Number(seconds); //set time with val from storage
}
startTimer(timeLeft, display);
};
I changed the name of your fiveMinutes to timeLeft to better reflect what it holds, and parsed both values to numbers with Number().
It's also important to mention that while this does keep the value after refreshes, it doesn't "count" the time while the page was closed. So keep that in mind.
Instead of refreshing the whole page try to use Ajax for communication and modify your html page using javascript.

How to prevent countdown timer from resetting when webpage is refreshed?

I am designing a website and I integrated a 5 minute countdown timer that starts when the web-page is loaded, using JavaScript. However, since I am more of a designer than a developer, I don't know how to edit the JavaScript code to make it so that the timer does not restart when the webpage is reloaded. I know I have to store the users cookies, and I've searched online, but the javascript code didnt work when I inserted the code. Would anyone here be able to help me out? Thank you!
Here is the javascript code for the 5 minute timer:
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + " " + " " + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
Check this approach where the time is stored in local storage of the browser and hence on refresh will not reset:
:HTML CODE:
<div id="time">
</div>
:JS CODE:
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + " " + " " + seconds;
if (--timer < 0) {
timer = duration;
}
console.log(parseInt(seconds))
window.localStorage.setItem("seconds",seconds)
window.localStorage.setItem("minutes",minutes)
}, 1000);
}
window.onload = function () {
sec = parseInt(window.localStorage.getItem("seconds"))
min = parseInt(window.localStorage.getItem("minutes"))
if(parseInt(min*sec)){
var fiveMinutes = (parseInt(min*60)+sec);
}else{
var fiveMinutes = 60 * 5;
}
// var fiveMinutes = 60 * 5;
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
Here is the working model of the same in the codepen https://codepen.io/anon/pen/GymRNV?editors=1011
P.S: couldn't use it here as it is a sandbox and cant access localstorage.
You should use web "Session storage" api for this case. it will much help you.
https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
sorry var distance = localStorage.getItem("mytime") - now;var x =localStorage.getItem("mytime"); I spent about 6 weeks figuring this out,it works,you need localstorage but only on countdown,now still has to function so counter counts,countdown is the anchor,look at w3school there countdown is set thats why it works,and thats were you use localstorage
use w3 school countdown timer,countdown date use localstorage.mytime=setDate(d.getDate + 7),also at end if distance < 0;localStorageremoveItem, thats it ,run code

javascript countdown echoing wrong time

i want this my javascript code to to be able to be reading 3 hours countdown and also redirect to a new page after the countdown is complete
<script type="text/javascript">
// properties
var count = 0;
var counter = null;
window.onload = function() {
initCounter();
};
function initCounter() {
// get count from localStorage, or set to initial value of 1000
count = getLocalStorage('count') || 1000;
counter = setInterval(timer, 1000); //1000 will run it every 1 second
}
function setLocalStorage(key, val) {
if (window.localStorage) {
window.localStorage.setItem(key, val);
}
return val;
}
function getLocalStorage(key) {
return window.localStorage ? window.localStorage.getItem(key) : '';
}
function timer() {
count = setLocalStorage('count', count - 1);
if (count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
document.getElementById("timer").innerHTML = hours + "hours " + minutes + "minutes and " + seconds + " seconds left to complete this transaction"; // watch for spelling
}
</script>
<div id="timer"></div>
please help me make it better by making it been able to countdown to three hour and also redirect to another page after the countdown is complete
You didn't properly set total time. You set it to 16 minutes instead of 3 hours. Here is the working code (try it on JSFiddle):
var time = 60 * 60 * 3;
var div = document.getElementById("timer");
var t = Date.now();
var loop = function(){
var dt = (Date.now() - t) * 1e-3;
if(dt > time){
doWhateverHere();
}else{
dt = time - dt;
div.innerHTML = `Hours: ${dt / 3600 | 0}, Minutes: ${dt / 60 % 60 | 0}, Seconds: ${dt % 60 | 0}`;
}
requestAnimationFrame(loop);
};
loop();
Also, do not use setInterval and setTimeout for precise timing. These functions are volatile. Use Date.now() instead.

Recursive countdown timer

I'm trying to create a javascript counter that starts at 25 minutes and ends at 0. the idea is to show the minutes/seconds as a countdown clock on the page (my target div is called 'txt'). But I'm not getting my desired result - the timer does not subtract each time the function is run (every ms). Any ideas on where I'm going wrong? Code is below:
function countdown() {
var target = 1500000; // 25 mins
var current = 1000; // 0 secs
for (var i=0; i<5; i++) {
var diff = target-current; // calculates the 25 minutes
var min = Math.floor(diff/1000/60); //gets mins
var sec = (diff/1000) % 60; // gets secs
current = current+1000;
document.getElementById("txt").innerHTML = min + ":" + sec;
var t = setTimeout(countdown, 2500);}
}
}
You need to define current outside of your function. Currently you are resetting it to 1000 every time the function is run.
here you go:
var target = 1500000; // 25 mins
var current = 0; // 0 secs
function countdown() {
current += 1000;
var diff = target-current; // calculates the 25 minutes
var min = Math.floor(diff/1000/60); //gets mins
var sec = (diff/1000) % 60; // gets secs
document.getElementById("txt").innerHTML = min + ":" + sec;
if (diff > 0)
setTimeout(countdown, 1000);
}
countdown();
JSFiddle with running example: https://jsfiddle.net/epcmw0uc/5/

Categories

Resources