I have developed a small bit of presentation software which consists of slides and assets for each slide. When a slide is rendered all of its assets are looped through and rendered after a delay using the setTimeout
method. looks sweet...
Yaaay!, requirements have changed, the presentation is now required to act like a PowerPoint slideshow, the mouse click event will cause the next asset to be rendered to the page immediately.
My question is; is there a way to cause my timeout to fire immediately? I can get and store in a stack the timeoutid as it is returned when the timeout is created. The only other option would be to cancel the timeout and then recreate the element, which is a lot more processing then i want to do, and I dont feel like refactoring my code too much.
Any ideas?
You could wrap it in a closure like this:
function createTimeout(timeoutHandler, delay) { var timeoutId; timeoutId = setTimeout(timeoutHandler, delay); return { clear: function() { clearTimeout(timeoutId); }, trigger: function() { clearTimeout(timeoutId); return timeoutHandler(); } }; } var a = new Date(); var timeout = createTimeout(function() { console.log(a); }, 1000); // timeout.clear(); timeout.trigger();
Updated (modern js):
let newTimeout = (handler, delay) => { let id = setTimeout(handler, delay), clear = clearTimeout.bind(null, id); return {id, clear, trigger: () => (clear(), handler())}; }; let timeout = newTimeout(() => console.log(new Date()), 1000); // timeout.clear(); timeout.trigger();
If you set the timer like this:
var timer1 = window.setTimeout(mainFunction,500)
call it immediately by doing this:
window.clearTimeout(timer1) mainFunction()
The key is to separate the function from the timer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With