报错TypeError: $.doTimeout is not a function,Laravel环境JS求助
TypeError: $.doTimeout is not a function in Laravel Hey there, let's work through this error you're hitting. The root cause here is pretty straightforward: $.doTimeout isn't a built-in jQuery method — it's a third-party plugin called jQuery doTimeout. If that plugin isn't properly loaded in your Laravel setup, jQuery won't recognize the method, hence the error.
Here's how to fix this step by step:
1. Make sure you're including the jQuery doTimeout plugin
You have two main ways to add this plugin to your Laravel project:
Option A: Install via npm (recommended for Laravel Mix/Vite)
- First, install the package:
npm install jquery-dotimeout - Next, import it in your
resources/js/app.jsfile (after importing jQuery):import $ from 'jquery'; import 'jquery-dotimeout'; // Your custom JS code goes here - Finally, compile your assets:
npm run dev # For development # OR npm run prod # For production
Option B: Use a CDN (quick test or small projects)
Add the plugin script after your jQuery script in your Blade template (e.g., resources/views/layouts/app.blade.php):
<!-- First load jQuery --> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <!-- Then load the doTimeout plugin --> <script src="https://cdn.jsdelivr.net/npm/jquery-dotimeout@1.0/jquery.doTimeout.min.js"></script> <!-- Finally load your custom JS --> <script> // Your code here $("p").click(function(){ $(this).hide(); }) $.doTimeout('myLoop', 5000, function() { ++i; timeleft = calctime(id, jsondata); document.getElementById("timeleft").innerHTML = timeleft; return i == 50 ? false : true; }); </script>
2. Double-check load order
This is critical: jQuery must load first, then the doTimeout plugin, then your custom JavaScript. If the plugin loads before jQuery, it can't attach itself to the $ object, and you'll still get the error.
3. Fix syntax errors in your code
Looking at your snippet, there's an extra }; at the end that doesn't belong. That could cause unexpected behavior or prevent your code from running correctly. Remove that trailing }; so your code looks clean:
$("p").click(function(){ $(this).hide(); }) $.doTimeout('myLoop', 5000, function() { ++i; timeleft = calctime(id, jsondata); document.getElementById("timeleft").innerHTML = timeleft; return i == 50 ? false : true; });
4. Vite-specific configuration (if you're using Vite)
If your Laravel project uses Vite instead of Mix, you need to make sure jQuery is properly aliased so the doTimeout plugin can find it. Update your vite.config.js:
import { defineConfig } from 'vite'; import laravel from 'laravel-vite-plugin'; import jquery from 'jquery'; export default defineConfig({ plugins: [ laravel({ input: ['resources/css/app.css', 'resources/js/app.js'], refresh: true, }), ], resolve: { alias: { '$': jquery, 'jQuery': jquery, }, }, });
After making these changes, clear your browser cache and reload the page — the error should be gone!
内容的提问来源于stack exchange,提问作者Octaaf

