I have Timer function, that does countdown. I move it from js to ts code
Here is code of function (TS)
export module Timer {
export function startTimer(duration, display){
let session_timer;
Date.now = Date.now || (() => +new Date);
const start = Date.now();
let diff = 0;
let minutes:any = 0;
let seconds:any = 0;
const timer = function() {
diff = duration - (((Date.now() - start) / 1000) | 0);
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
if (minutes < 0) { minutes = "0"; }
if (seconds < 0) { seconds = "0"; }
minutes = minutes < 10 ? `0${minutes}` : minutes;
seconds = seconds < 10 ? `0${seconds}` : seconds;
display.html(`${minutes}:${seconds}`);
if (diff <= 0) {
$(this).changePage('#session_timer');
return clearInterval(session_timer);
}
};
timer();
return session_timer = setInterval(timer, 1000);
};
}
export default Timer;
I importing it to index.ts, webpack component like this
import Timer from "./scripts/timer";
export default Timer;
And than call in step2.js pack
Like this
import Timer from "../components/timer";
$(document).ready(() => {
Timer.startTimer();
});
But when I try to run project I have this error
TypeError: Cannot read property 'html' of undefined
JS Code is was this
window.startTimer = function(duration, display) {
let session_timer;
Date.now = Date.now || (() => +new Date);
const start = Date.now();
let diff = 0;
let minutes = 0;
let seconds = 0;
const timer = function() {
diff = duration - (((Date.now() - start) / 1000) | 0);
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
if (minutes < 0) { minutes = "0"; }
if (seconds < 0) { seconds = "0"; }
minutes = minutes < 10 ? `0${minutes}` : minutes;
seconds = seconds < 10 ? `0${seconds}` : seconds;
display.html(`${minutes}:${seconds}`);
if (diff <= 0) {
$(this).changePage('#session_timer');
return clearInterval(session_timer);
}
};
timer();
return session_timer = setInterval(timer, 1000);
};
How I can fix it? In JS all working great
displayvariable. Where is it defined? Apparently is not, and hence the error.undefined. Check it withconsole.log(display)just before callingdisplay.htmldisplayto be? You might have to explicitly annotate it:display: JQuery.