Reputation: 11
I need to define a single function that handles the functionality provided by setSlide, setMobile, and hide and just pass in the function to be called by SetTimeout when the delay has occurred. I'm not sure how to do this. Can someone please explain how to accomplish this? Thank you.
(function($) {
var currentTime = new Date().getTime() / 1000;
var setSlide = function (timeout) {
setTimeout(showSlide, timeout * 1000);
},
showSlide = function () {
$('.newsletter-popup').addClass('slide-left');
},
setMobile = function (timeout) {
setTimeout(showMobile, timeout * 1000);
},
hide = function (timeout) {
setTimeout(hideMobile, timeout * 1000);
},
showMobile = function () {
$('.newsletter-popup').removeClass('hidden');
},
hideMobile = function () {
$('.newsletter-popup').addClass('hidden');
};
$(document).ready(function() {
if (readCookie('nl_suppress')) {
$('.newsletter-popup').removeClass('slide-left');
} else if (!readCookie('nl_display')) {
setSlide(10);
} else if (currentTime - readCookie('nl_display') > 86400) {
showSlide();
} else {
setSlide(currentTime - (readCookie('nl_display') + 86400));
}
$('.nlForm').submit(function() {
createCookie('nl_suppress', new Date(), 30);
});
function checkCookie() {
var date = new Date();
date.setTime(date.getTime() + (86400000));
$('.newsletter-popup').removeClass('slide-left');
hide(1);
if(readCookie('nl_display')) {
// already been clicked once, hide it
createCookie('nl_suppress', new Date(), 180);
return;
}
// first time this is clicked, mark it
createCookie('nl_display', new Date().getTime() / 1000, 180);
setMobile(14);
setSlide(15);
};
$('.newsletter-close').on('click', checkCookie);
});
})(jQuery);
Upvotes: 1
Views: 41
Reputation: 33476
It sounds like you want to create a function that does the same thing as setTimeout
, but the delay multiplied by 1000
so that it is in seconds.
It would look like this:
function setTimeoutSeconds(func, delay) {
setTimeout(func, delay * 1000);
}
Then instead of calling setSlide
, setMobile
, or hide
, you call setTimeoutSeconds
with the desired callback.
setTimeoutSeconds(hideMobile, 1);
setTimeoutSeconds(showMobile, 14);
setTimeoutSeconds(showSlide, 15);
If you still wanted to have the setSlide
... etc functions, you could use a partially applied function:
function applyTimeout(func) {
return function(delay) {
setTimeout(func, delay * 1000);
}
}
And then create them like this:
var setSlide = applyTimeout(showSlide);
And then call them the same way:
setSlide(15);
Upvotes: 2
Reputation: 92521
It's really simple:
const callFunctionWithTimeout = (fn, timeout) => setTimeout(fn, timeout * 1000)
Then, for example instead of setSlide(10)
, you do:
callFunctionWithTimeout(showSlide, 10)
Upvotes: 1